简体   繁体   English

如何从另一个线程访问 WinForms 控件,即与 GUI 线程同步?

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

I'm working on C# winforms app and i need to know how to manupilate a code into a thread by changing checkbox value.我正在开发 C# winforms 应用程序,我需要知道如何通过更改复选框值将代码操作到线程中。

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

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

You can use this:你可以使用这个:

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

  TcpListener server = null;

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

Or:或者:

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

Having:有:

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;
  }

}

Adding in the Program.Main before the Application.Run:在 Application.Run 之前添加 Program.Main:

SyncUIHelper.Initialize();

You can find on stack overflow various ways to synchronize threads with the UI thread like:您可以在堆栈溢出中找到各种将线程与 UI 线程同步的方法,例如:

How do I update the GUI from another thread? 如何从另一个线程更新 GUI?

There is BackgroundWorker too.也有 BackgroundWorker。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM