1. 程式人生 > >winform 多執行緒,操作主執行緒使用者介面

winform 多執行緒,操作主執行緒使用者介面

winform程式設計,在子執行緒中操作介面元素,之前有一種比較複雜 的寫法,用了delegate。昨天在《C#本質論》中看到了一種比較簡潔的寫法,分享如下:

//有個label,名稱是lblWeather,子執行緒中獲取了天氣資訊,要顯示在這個label上
 
private void updateWeatherInfo()
 {
     if (lblWeather.InvokeRequired)
     {
        MethodInvoker ivk = updateWeatherInfo;
        lblWeather.BeginInvoke(ivk);
     }
     else
     {
        lblWeather.Text = weatherInfo; //本類的全域性變數
     }
 }

缺點是不方便直接傳引數,要用全域性變數中轉一下。