【发布时间】:2014-07-17 16:00:19
【问题描述】:
我对编程和 WPF 架构非常陌生。我有一个使用 backgroundworker 类的 WPF 应用程序。但是,它总是抛出错误“调用线程必须是 sta,因为许多 ui 组件需要这个”。我需要在我的主要方法中添加 STAThread 属性。但我不知道该怎么做。
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.backgroundWorker1 = new System.ComponentModel.BackgroundWorker();
InitializeBackgroundWorker();
Thread.CurrentThread.SetApartmentState(ApartmentState.STA);
tabItemList.CollectionChanged += this.TabCollectionChanged;
}
}
private void InitializeBackgroundWorker()
{
backgroundWorker1.DoWork +=
new DoWorkEventHandler(backgroundWorker1_DoWork);
backgroundWorker1.RunWorkerCompleted +=
new RunWorkerCompletedEventHandler(
backgroundWorker1_RunWorkerCompleted);
backgroundWorker1.ProgressChanged +=
new ProgressChangedEventHandler(
backgroundWorker1_ProgressChanged);
}
// This event handler is where the actual,
// potentially time-consuming work is done.
private void backgroundWorker1_DoWork(object sender,
DoWorkEventArgs e)
{
// Get the BackgroundWorker that raised this event.
BackgroundWorker worker = sender as BackgroundWorker;
// Assign the result of the computation
// to the Result property of the DoWorkEventArgs
// object. This is will be available to the
// RunWorkerCompleted eventhandler.
//e.Result = AddTabitem((int)e.Argument, worker, e);
AddTabitem((string)e.Argument, worker, e);
}
void AddTabitem(string filePath, BackgroundWorker worker, DoWorkEventArgs e)
{
if (File.Exists(filePath))
{
//This line which throws error "the calling thread must be sta because many ui components require this"
RichTextBox mcRTB = new RichTextBox();
rtbList.Add(mcRTB);
}
【问题讨论】:
-
除了同意 democodemonkey 的回答之外,您还应该查看“任务”类。
-
您几乎没有理由考虑使用
BackgroundWorker。一方面,如果您使用 MVVM/Binding,您将拥有自动 UI 线程封送处理。另一方面,您应该将Task.Run用于任何 CPU 密集型计算和异步任务 I/O 用于任何 I/O 密集型操作。
标签: c# wpf backgroundworker