我是编程和WPF架构的新手.我有一个使用backgroundworker类的WPF应用程序.但是,它总是抛出错误“调用线程必须是sta,因为许多ui组件都需要它”.我需要在我的main方法中添加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);
}
解决方法:
您必须在启动线程之前设置ApartmentState.
http://blogs.msdn.com/b/jfoscoding/archive/2005/04/07/406341.aspx
要在您的WPF应用中设置公寓状态,
将[STAThread]属性添加到您的应用程序中,例如this:
public partial class App : Application
{
App()
{
InitializeComponent();
}
[STAThread]
static void Main()
{
Window1 window = new Window1();
App app = new App();
app.Run(window);
}
}