【发布时间】:2013-03-18 17:40:38
【问题描述】:
在我的 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
{--------- }
问候 桑吉塔
【问题讨论】:
-
什么是_listFiles?另外:请尝试格式化以提高可读性。
-
_listFiles 是名称列表视图控件。浏览文件并将其添加到列表视图。
-
从发布的代码中我想说:根本不要使用线程。