在我的 wpf 应用程序中,我将按钮单击事件作为单独的线程并作为后台进程运行,以便 UI 响应用户。代码如下,
private void btn_convert_Click(object sender, RoutedEventArgs e)
{
//Makes the conversion process as background task which
//makes the UI responsive to the user.
Thread thread = new Thread(new ThreadStart(WorkerMethod));
thread.SetApartmentState(ApartmentState.MTA);
thread.IsBackground = true;
thread.Start();
}
在 WorkerMethod 中,我可以选择更改为用户提供单独窗口的文件名。对于此操作,我使用 Dispatcher 方法,如下所示,
if (MessageBox.Show("Do you want to set filename?",
"Information", MessageBoxButton.YesNo, MessageBoxImage.Asterisk) ==
MessageBoxResult.Yes)
{
Action showOutput = () =>
{
BlueBeamConversion.SetOutput _setOutput =
new BlueBeamConversion.SetOutput();
_setOutput.ShowDialog();
};
Dispatcher.BeginInvoke(showOutput);
if (String.IsNullOrEmpty(MainWindow.destinationFileName))
return;
其中destinationFileName 将在SetOutput 窗口中设置。现在来谈谈我的问题,当上面的代码执行时,SetOutput 窗口会出现并且不会等到我设置文件名。在设置文件名之前,它涉及以下代码,
if (String.IsNullOrEmpty(MainWindow.destinationFileName))
return;
在 setoutput 窗口中单击“确定”按钮之前,我该如何坚持。欢迎提出任何建议。
我使用了 dispatcher.Invoke 而不是 BeginInvoke。现在它持有窗口并采用新名称。但是,当在某一行继续工作方法中的代码时,它会退出应用程序本身,请对代码进行罚款,
if (MessageBox.Show("Do you want to set filename?", "Information", MessageBoxButton.YesNo, MessageBoxImage.Asterisk) == MessageBoxResult.Yes)
{
Action showOutput = () =>
{ BlueBeamConversion.SetOutput _setOutput = new BlueBeamConversion.SetOutput(); _setOutput.ShowDialog(); };
Dispatcher.Invoke(showOutput);
for (int i = 0; i < _listFiles.Items.Count; i++)--- here it exits
{--------- }
问候桑吉塔