C#如何检查对话框是否仍然打开?

时间:2014-03-07 02:52:06

标签: c# backgroundworker

所以我有一个后台工作者,当关闭事件发生时可能仍在工作。

我这样调用cancelasync():

void ProgressDialog_Closing(object sender, CancelEventArgs e)
{
  if (_worker.IsBusy)
  {
    //notifies the async thread that a cancellation has been requested.
    _worker.CancelAsync();
  }
}

但是,由于我的runworker_completed方法,我遇到崩溃,该方法声明在对话框未打开时无法设置对话框结果。如何检查对话框是否仍处于打开状态?

void _worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
      if (!Dispatcher.CheckAccess())
      {
        //run on UI thread
        RunWorkerCompletedEventHandler handler = _worker_RunWorkerCompleted;
        Dispatcher.Invoke(handler, null, DispatcherPriority.SystemIdle, new object[] { sender, e });
        return;
      }
      else
      {
        if (e.Error != null)
        {
          error = e.Error;
        }
        else if (!e.Cancelled)
        {
          //assign result if there was neither exception nor cancel
          result = e.Result;
        }
        ProgressBar.Value = ProgressBar.Maximum;
        CancelButton.IsEnabled = false;


        //set the dialog result, which closes the dialog

        if (error == null && !e.Cancelled)
        {
          DialogResult = true;
        }
        else
        {
          DialogResult = false;
        }

      }

    }

构造函数没什么特别,runworkerthread是启动worker并设置委托运行的原因。

public bool RunWorkerThread(object argument, Func<object> workHandler)
    {
      //store reference to callback handler and launch worker thread
      workerCallback = workHandler;
      _worker.RunWorkerAsync(argument);


      return ShowDialog() ?? false;
    }

1 个答案:

答案 0 :(得分:1)

    DialogBox dialogBox = new DialogBox();

    // Show window modally 
    // NOTE: Returns only when window is closed
    Nullable<bool> dialogSelection = dialogBox.ShowDialog();
    if dialogSelection = null // box is still open

http://msdn.microsoft.com/en-us/library/system.windows.window.showdialog(v=vs.110).aspx

我认为在用户进行选择或框关闭之前,dialogSelection为null。