在我的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。现在它保持窗口并取新名称。但是当工作方法中的代码继续某一行退出应用程序本身时,请将代码罚款为bekow,
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
{--------- }
此致 桑杰塔
答案 0 :(得分:1)
使用ShowDialog()而不是Show()并将输出存储在DialogResult中
var result = _setOutput.ShowDialog();
答案 1 :(得分:1)
您可以使用Invoke而不是BeginInvoke:
//Dispatcher.BeginInvoke(showOutput);
Dispatcher.Invoke(showOutput);
答案 2 :(得分:0)
当你在你的动作中使用window.show()方法时,你不会从show方法得到任何结果,你必须调用窗口的show dialog方法,这将强制GUI保持直到对话窗口关闭,之后,您将能够从对话框windo中重新获取数据。
Action showOutput = () =>
{ BlueBeamConversion.SetOutput _setOutput = new BlueBeamConversion.SetOutput(); _setOutput.ShowDialog(); };
Dispatcher.BeginInvoke(showOutput);
另一方面,你可以先等待线程完成,直到你可以等待。这个approch也适合你。 dispatcher.Invoke会帮助你。你可以在这里尝试DispatcherOperation。
尝试使用以下更改的代码。
DispatcherOperation op = Dispatcher.BeginInvoke(showOutput);
op.Wait();
if (String.IsNullOrEmpty(output))
return;
答案 3 :(得分:0)
如果您使用ShowDialog,您可以将值存储在第二个窗口的公共属性中,并可以通过以下方式访问它:
Form2 form2 = new Form2();
if (form2.ShowDialog() == DialogResult.OK)
{
if (form2.ReturnData == "myResult")
... }