簡體   English   中英

如何從另一個線程訪問 WinForms 控件,即與 GUI 線程同步?

[英]How to access a WinForms control from another thread i.e. synchronize with the GUI thread?

我正在開發 C# winforms 應用程序,我需要知道如何通過更改復選框值將代碼操作到線程中。

 new Thread(() =>
        {
            Thread.CurrentThread.IsBackground = true;

            TcpListener server = null;
            while (true)
            {
                if(){}else{}// here I need to check my checkbox
}}).Start();

你可以使用這個:

new Thread(() =>
{
  Thread.CurrentThread.IsBackground = true;

  TcpListener server = null;

  while (true)
  {
    ...
    this.SynUI(()=>
    {
      if ( checkbox.Checked )
      {
      }
    });
    ...
  }
}).Start();

或者:

...
bool checked = false;
this.SynUI(()=> { checked = checkbox.Checked; });
...

有:

static public class SyncUIHelper
{
  static public Thread MainThread { get; private set; }

  // Must be called from the Program.Main or the Main Form constructor for example
  static public void Initialize()
  {
    MainThread = Thread.CurrentThread;
  }

  static public void SyncUI(this Control control, Action action, bool wait = true)
  {
    if ( !Thread.CurrentThread.IsAlive ) throw new ThreadStateException();
    Exception exception = null;
    Semaphore semaphore = null;
    Action processAction = () =>
    {
      try { action(); }
      catch ( Exception except ) { exception = except; }
    };
    Action processActionWait = () =>
    {
      processAction();
      if ( semaphore != null ) semaphore.Release();
    };
    if ( control != null
      && control.InvokeRequired
      && Thread.CurrentThread != MainThread )
    {
      if ( wait ) semaphore = new Semaphore(0, 1);
      control.BeginInvoke(wait ? processActionWait : processAction);
      if ( semaphore != null ) semaphore.WaitOne();
    }
    else
      processAction();
    if ( exception != null ) throw exception;
  }

}

在 Application.Run 之前添加 Program.Main:

SyncUIHelper.Initialize();

您可以在堆棧溢出中找到各種將線程與 UI 線程同步的方法,例如:

如何從另一個線程更新 GUI?

也有 BackgroundWorker。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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