【发布时间】:2015-08-19 18:34:00
【问题描述】:
您可以在 SO 上找到很多类似的问题,但没有人(如我所见)涵盖情况,当您的逻辑必须返回某些内容时。
在这个代码示例中,我有一个简单的 CustomMessageBox(它是一个窗口),它必须返回由用户输入的内容。
public class CustomMessageBox
{
private string Value
{
get
{
return txt_box.Text;
}
}
private CustomMessageBox ()
{
InitializeComponent();
}
public static string Show(string caption = "Enter data")
{
CustomMessageBox cmb = new CustomMessageBox ();
cmb.txt_block.Text = caption;
cmb.ShowDialog();
return cmb.Value;
}
}
因此,当BackgroundWorker 调用Show 方法时,当构造函数尝试执行时,在第一行抛出异常。异常消息是
An exception of type 'System.InvalidOperationException' occurred in
PresentationCore.dll but was not handled in user code
Additional information: The calling thread must be STA,
because many UI components require this.
没有什么新东西,但我找不到这个问题的解决方案,我不能让线程成为 STA。 Show 方法签名必须像这样清晰 - 接受字符串并返回字符串。
通常必须如何解决此类问题?
【问题讨论】:
-
您可以使用dispatcher.Invoke 使线程成为STA
-
请提供任何能够从执行中返回值的示例。
-
我通常以相反的方式执行此操作(至少在 WinForms 中):我订阅了 Close-event 并在事件处理程序中获取我需要的值,而不是返回一些东西。
-
但我不能。需要明确的退货。
标签: c# multithreading dispatcher ui-thread