调度员.在c#中调用另一个窗口

本文关键字:另一个 窗口 调用 调度员 | 更新日期: 2023-09-27 18:04:32

在我的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;

我怎么能保持,直到我点击确定按钮在设置输出窗口。欢迎提出任何建议。

我使用了dispatcher。调用而不是BeginInvoke。现在它保留了窗口并获得了新名称。但是当workmethod在某一行中继续执行代码时,它会退出应用程序本身,请将代码定义为

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
                {--------- }

的问候sangeetha

调度员.在c#中调用另一个窗口

使用ShowDialog()代替Show(),并将输出存储在dialgresult

 var result = _setOutput.ShowDialog();

你可以用Invoke代替BeginInvoke:

 //Dispatcher.BeginInvoke(showOutput);
 Dispatcher.Invoke(showOutput);

如果您使用ShowDialog,您可以将该值存储在第二个窗口的公共属性中,并可以像这样访问它:

Form2 form2 = new Form2();
if (form2.ShowDialog() == DialogResult.OK)
{
if (form2.ReturnData == "myResult")

…}

当你在操作中使用window.show()方法时,你将不会从show方法中收到任何结果,相反,你必须调用window的show dialog方法,该方法将强制GUI保持直到对话框窗口关闭,之后你将能够从对话框窗口接收数据。

 Action showOutput = () =>
                            { BlueBeamConversion.SetOutput _setOutput = new BlueBeamConversion.SetOutput(); _setOutput.ShowDialog(); }; 
                        Dispatcher.BeginInvoke(showOutput);

,另一方面,你可以先等待线程完成,直到你可以等待。这种方法也适用于您。调度程序。Invoke将帮助您。或者你可以试试DispatcherOperation。

尝试修改下面的代码。

  DispatcherOperation op = Dispatcher.BeginInvoke(showOutput);
                op.Wait();
                if (String.IsNullOrEmpty(output))
                    return;