C#多線程更新界面有多種方法:
1. 使用Application.DoEvents();
2. 使用委託delegate
3. 使用BackgroundWorker; 最偷懶的辦法(Winform/Silverlight通用)
4. 設置Control.CheckForIllegalCrossThreadCalls爲false,相當於不檢測線程之間的衝突
5. Dispatcher.BeginInvoke--Silverlight的獨門祕籍
6. 利用SynchronizationContext上下文 -- 最神祕的方法(Winform/Silverlight能用)
先記錄一種方法,使用委託來更新UI,其他的方法暫時還沒研究:
1、
public delegate void LoadDataDelegate();
public LoadDataDelegate loadDelegate;
public void LoadContent()
{
loadDelegate = new LoadDataDelegate(LoadData);
this.BeginInvoke(loadDelegate);
}
private void InitProvinceData()
{
//這裏面就可以對UI進行更新了
}
public delegate void ShowWeatherDelegate();
private void ShowWeather()
{
if (weatherInterface.InvokeRequired)
{
ShowWeatherDelegate showDelegate = new ShowWeatherDelegate(ShowWeather);
this.BeginInvoke(showDelegate);
}
else
{
weatherInterface.Visible = true;
waitInterface1.Visible = false;
}
}