程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> WPF多線程-1

WPF多線程-1

編輯:C#入門知識

先上代碼:

[csharp]
public partial class MainWindow : Window 
    { 
        public MainWindow() 
        { 
            InitializeComponent(); 
            Thread t = new Thread(new ParameterizedThreadStart(threadTest)); 
            t.Start(@"C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg"); 
        } 
 
        void threadTest(object obj) 
        { 
            string path = obj as string; 
            this.Dispatcher.Invoke(new Func<object>(() => this.Background = new ImageBrush(new BitmapImage(new Uri(path))))); 
        } 
    } 

 

上面這段代碼可以正確運行,但是該成如下形式的就錯誤了:

[html]
public partial class MainWindow : Window 
    { 
        public MainWindow() 
        { 
            InitializeComponent(); 
            Thread t = new Thread(new ParameterizedThreadStart(threadTest)); 
            t.Start(@"C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg"); 
        } 
 
        void threadTest(object obj) 
        { 
            string path = obj as string; 
            //this.Dispatcher.Invoke(new Func<object>(() => this.Background = new ImageBrush(new BitmapImage(new Uri(path))))); 
            ImageBrush background = new ImageBrush(new BitmapImage(new Uri(path))); 
            this.Dispatcher.Invoke(new Func<object>(() => this.Background = background)); 
        } 
    } 

兩個代碼的唯一區別是,前一個代碼在主線程中創建ImageBrush對象,而後一個代碼在子線程中創建ImageBrush對象。

難道WPF中,所有線程只能調用本線程創建的對象嗎?


摘自 I have a adream

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved