簡體   English   中英

"如何訪問 UI 線程?"

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM