10 c# user-interface multithreading
当我尝试更改UI属性(特别是启用)时,我的线程抛出System.Threading.ThreadAbortException
我如何访问线程中的UI.
ben*_*rwb 20
您可以使用BackgroundWorker,然后像这样更改UI:
control.Invoke((MethodInvoker)delegate {
control.Enabled = true;
});
Run Code Online (Sandbox Code Playgroud)
如果您使用的是C#3.5,那么使用扩展方法和lambdas来防止从其他线程更新UI非常容易.
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
因此,现在您可以InvokeEx
在任何表单上使用,并能够访问不属于的任何属性/字段Form
.
this.InvokeEx(f => f.label1.Text = "Hello");
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8546 次 |
最近记录: |