本文介绍了如何从另一个线程访问WinForms控件,即与GUI线程同步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用C#winforms应用程序,我需要知道如何通过更改复选框值来将代码操纵到线程中.

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(() =>
        {
            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.Main之前添加Program.Main.运行:

Adding in the Program.Main before the Application.Run:

SyncUIHelper.Initialize();

您可以在堆栈溢出中找到将线程与UI线程同步的各种方法,例如:

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

如何从另一个线程更新GUI? /a>

How do I update the GUI from another thread?

也有BackgroundWorker.

There is BackgroundWorker too.

这篇关于如何从另一个线程访问WinForms控件,即与GUI线程同步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!