同步上下文 SynchronizationContext 學習筆記

來源:互聯網
上載者:User
文章目錄
  • 同步內容相關的基本操作

提供在各種同步模型中傳播同步內容相關的準系統。,同步內容相關的工作就是確保調用在正確的線程上執行。

 

同步內容相關的基本操作Current 擷取當前同步上下文
var context = SynchronizationContext.Current;
Send 一個同步訊息調度到一個同步上下文。

 

SendOrPostCallback callback = o =>
{
//TODO:
};
context.Send(callback,null);

send調用後會阻塞直到調用完成。

Post 將非同步訊息調度到一個同步上下文。
SendOrPostCallback callback = o =>
{
//TODO:
};
context.Post(callback,null);

和send的調用方法一樣,不過Post會啟動一個線程來調用,不會阻塞當前線程。

 

使用同步上下文來更新UI內容

無論WinFroms和WPF都只能用UI線程來更新介面的內容

常用的調用UI更新方法是Inovke(WinFroms):

private void button_Click(object sender, EventArgs e)
{
ThreadPool.QueueUserWorkItem(BackgroudRun);
}

private void BackgroudRun2(object state)
{
this.Invoke(new Action(() =>
{
label1.Text = "Hello Invoke";
}));
}

 

 

使用同步上下文也可以實現相同的效果,

WinFroms和WPF繼承了SynchronizationContext,使同步上下文能夠在UI線程或者Dispatcher線程上正確執行

System.Windows.Forms. WindowsFormsSynchronizationContext
System.Windows.Threading. DispatcherSynchronizationContext

 

調用方法如下:

private void button_Click(object sender, EventArgs e)
{
var context = SynchronizationContext.Current; //擷取同步上下文
Debug.Assert(context != null);
ThreadPool.QueueUserWorkItem(BackgroudRun, context);
}


private void BackgroudRun(object state)
{
var context = state as SynchronizationContext; //傳入的同步上下文
Debug.Assert(context != null);
SendOrPostCallback callback = o =>
{
label1.Text = "Hello SynchronizationContext";
};
context.Send(callback,null); //調用
}

使用.net4.0的Task 可以簡化成

private void button_Click(object sender, EventArgs e)
{
var scheduler = TaskScheduler.FromCurrentSynchronizationContext(); // 建立一個SynchronizationContext 關聯的 TaskScheduler
Task.Factory.StartNew(() => label1.Text = "Hello TaskScheduler", CancellationToken.None,
TaskCreationOptions.None, scheduler);
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.