WinformWPF 多線程訪問控制項【轉】

來源:互聯網
上載者:User

標籤:建立線程   object   pat   修改   啟用   線程id   lin   new   eth   

大家知道WPF中多線程訪問UI控制項時會提示UI線程的資料不能直接被其他線程訪問或者修改,該怎樣來做呢?

分下面兩種情況

1.WinForm程式

1)第一種方法,使用委託:private delegate void SetTextCallback(string text);        private void SetText(string text)        {            // InvokeRequired需要比較調用線程ID和建立線程ID            // 如果它們不相同則返回true            if (this.txt_Name.InvokeRequired)            {                SetTextCallback d = new SetTextCallback(SetText);                this.Invoke(d, new object[] { text });            }            else            {                this.txt_Name.Text = text;            }        }2)第二種方法,使用匿名委託        private void SetText(Object obj)        {            if (this.InvokeRequired)            {                this.Invoke(new MethodInvoker(delegate                {                    this.txt_Name.Text = obj;                }));            }            else            {                this.txt_Name.Text = obj;            }        }這裡說一下BeginInvoke和Invoke和區別:BeginInvoke會立即返回,Invoke會等執行完後再返回。

Winform也可以直接設定啟用多線程訪問屬性的設定,委託之類的也就可以不用添加了。

2.WPF程式

1)可以使用Dispatcher執行緒模式來修改

如果是表單本身可使用類似如下的代碼:

this.lblState.Dispatcher.Invoke(new Action(delegate{     this.lblState.Content = "狀態:" + this._statusText;}));

那麼假如是在一個公用類中彈出一個視窗、播放聲音等呢?這裡我們可以使用:System.Windows.Application.Current.Dispatcher,如下所示

System.Windows.Application.Current.Dispatcher.Invoke(new Action(() => {     if (path.EndsWith(".mp3") || path.EndsWith(".wma") || path.EndsWith(".wav"))     {        _player.Open(new Uri(path));        _player.Play();    } }));

 

WinformWPF 多線程訪問控制項【轉】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.