C# 如何从另一个线程(即与GUI线程同步)访问WinForms控件?
我正在开发C#winforms应用程序,我需要知道如何通过更改复选框值将代码制作成线程C# 如何从另一个线程(即与GUI线程同步)访问WinForms控件?,c#,multithreading,winforms,C#,Multithreading,Winforms,我正在开发C#winforms应用程序,我需要知道如何通过更改复选框值将代码制作成线程 new Thread(() => { Thread.CurrentThread.IsBackground = true; TcpListener server = null; while (true) { if(){}else{}// here I need
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();
或:
具有:
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;
}
}
在应用程序之前添加Program.Main。运行:
SyncUIHelper.Initialize();
您可以在堆栈溢出上找到各种方法来将线程与UI线程同步,如:
也有BackgroundWorker。请阅读以了解堆栈溢出的工作原理,并阅读如何提高问题的质量。然后,你的问题包括你的完整源代码,你有作为一个,它可以被编译和测试的其他人。
SyncUIHelper.Initialize();