BackgroundWorker 线程必须是 STA [英] BackgroundWorker thread must be STA
问题描述
我有一个BackgroundWorker来调用一个函数在BackgroundWorker _DoWork上做一个很长的过程,当函数发生错误时我会提示一个自定义的消息框:
I have a BackgroundWorker to call a function to do a long process at BackgroundWorker _DoWork, when error occur in the function I will prompt a customized messagebox:
WPFMessageBoxResult result = WPFMessageBox.Show("Activation Fail", "Error!!", WPFMessageBoxButtons.OK, WPFMessageBoxImage.Error);
以下异常发生在 WPFMessageBoxResult 类:
The exception below happens at WPFMessageBoxResult class :
The calling thread must be STA, because many UI components require this.
谢谢.
推荐答案
您不应尝试从后台线程与任何 UI 组件进行交互.
You should not try to interact with any UI components from a background thread.
一种方法是在 doWork 方法中捕获异常并将其分配给后台工作器的 result 属性,然后检查该结果是否为异常类型,或者如果您不将结果用于其他任何事情,则检查该结果是否为空.然后在 backgroundWorker_completed 事件中检查它.
One way could be to catch the exception in your doWork method and assign it to the backgroundworker's result property and then check if that result is a type of exception or not null if you are not using the result for anything else. then check for it in the backgroundWorker_completed event.
BackgroundWorker_DoWork(sender, )
{
try
{
// do work
}
catch (Exception ex)
{
BackgroundWorker w = sender as BackgroundWorker;
if (w != null)
w.Result = ex;
}
}
然后
BackgroundWorker_Completed()
{
if (s.Result != null && e.Result is Exception)
{
Exception ex = e.Result as Exception;
// do something with ex
}
}
这篇关于BackgroundWorker 线程必须是 STA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!