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

前端 未结 1 1553
礼貌的吻别
礼貌的吻别 2020-12-11 14:26

I\'m working on C# winforms app and i need to know how to manupilate a code into a thread by changing checkbox value.

 new Thread(() =>
        {
                 


        
相关标签:
1条回答
  • 2020-12-11 15:16

    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:

    SyncUIHelper.Initialize();
    

    You can find on stack overflow various ways to synchronize threads with the UI thread like:

    How do I update the GUI from another thread?

    There is BackgroundWorker too.

    0 讨论(0)
提交回复
热议问题