当我尝试更改UI属性(特别是启用)时,我的线程会抛出System.Threading.ThreadAbortException异常。
如何在线程中访问UI。
当我尝试更改UI属性(特别是启用)时,我的线程会抛出System.Threading.ThreadAbortException异常。
如何在线程中访问UI。
你可以使用BackgroundWorker,然后像这样更改UI:
control.Invoke((MethodInvoker)delegate {
control.Enabled = true;
});
public static class FormExtensions
{
public static void InvokeEx<T>(this T @this, Action<T> action) where T : Form
{
if (@this.InvokeRequired)
{
@this.Invoke(action, @this);
}
else
{
action(@this);
}
}
}
现在您可以在任何窗体上使用InvokeEx
并能够访问不属于Form
的任何属性/字段。
this.InvokeEx(f => f.label1.Text = "Hello");
我假设我们在谈论WinForms?你需要有一个单一的线程来管理这个 - 创建相关控件的线程。如果你想从不同的线程中执行此操作,可以使用Control.InvokeRequired检测到,然后应该使用Control.Invoke方法将其调度到正确的线程上。搜索该属性和方法(分别)以获取一些常见的模式。
void button1_Click( object sender, EventArgs e ) {
var thread = new Thread( ParalelMethod );
thread.Start( "hello world" );
}
void ParalelMethod( object arg ) {
if ( this.InvokeRequired ) {
Action<object> dlg = ParalelMethod;
this.Invoke( dlg, arg );
}
else {
this.button1.Text = arg.ToString();
}
}
如果您想在非 UI 线程仍在运行时修改 UI,请使用 SynchronizationContext
来调度对 UI 线程的调用。否则,请使用 BackgroundWorker
。