1)Issue:
private void button1_Click(object sender, RoutedEventArgs e)
{
BackgroundWorker bw_test = new BackgroundWorker();
bw_test.DoWork += new DoWorkEventHandler(bw_test_DoWork);
bw_test.RunWorkerAsync();
}
void bw_test_DoWork(object sender, DoWorkEventArgs e)
{
try
{
//show another Forms
InputCvtDefManul put = new InputCvtDefManul();
put.ShowDialog();
}
catch (Exception ex)
{ }
}
Encounter this error: The calling thread must be STA, because many UI components require this
2) 经过尝试,有两种方式可以解决:
A.这种方法网上有很多,如果不需要交互(等待显示Form的数据),或者仅仅是更新其显示Form的数据,这个就足够解决了。
void bw_test_DoWork(object sender, DoWorkEventArgs e)
{
try
{
//InputCvtDefManul put = new InputCvtDefManul();
//put.ShowDialog();
Thread newWindowThread = new Thread(new ThreadStart(() =>
{
Dispatcher.Invoke(new Action(() =>
{
InputCvtDefManul ss = new InputCvtDefManul();
ss.ShowDialog();
}));
}));
newWindowThread.Start();
newWindowThread.SetApartmentState(ApartmentState.STA);
newWindowThread.IsBackground = false;
newWindowThread.Start();
}
catch (Exception ex)
{ }
}
B.使用当前进程:
void bw_test_DoWork(object sender, DoWorkEventArgs e)
{
try
{
System.Windows.Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new DoMywork(ThreadStartingPoint));
MessageBox.Show("iii", "Info", MessageBoxButton.OK, MessageBoxImage.Information);
}
catch (Exception ex)
{ }
}
private delegate void DoMywork();
private void ThreadStartingPoint()
{
InputCvtDefManul put = new InputCvtDefManul();
put.ShowDialog();
}
这样的结果是只有在另起的Form关闭后才会弹出一个MessageBox。(异步)