[英]How to access the UI thread?
我有一個執行簡單任務的 Winform APP。 有一個用於創建新線程的按鈕的事件偵聽器:
ThreadStart work = (addToList);
Thread thread = new Thread(work);
thread.Start();
Invoke<\/code>方法需要一個委托(對函數的引用)並將其安排在 UI 線程上。
考慮到表單上的所有元素與 UI 線程共享同一個線程,您可以從表單或其任何控件中使用
Invoke<\/code>方法:
class MyForm
{
private void Button_Click(object sender, EventArgs e)
{
var thread = new Thread(new ThreadStart(FullCalculation));
thread.Start();
}
private void FullCalculation()
{
OffUIThreadCalculation();
this.Invoke(OnUIThreadCalculation); // Schedules OnUIThreadCalculation to run on the UI thread of `this`, aka the form
}
private void OffUIThreadCalculation()
{
// UI elements should not be used here
}
private void OnUIThreadCalculation()
{
// UI elements can be used here
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.