我对编程和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);
}