Display “Wait” screen in WPF

前端 未结 4 1126
粉色の甜心
粉色の甜心 2020-12-13 11:26

I am trying to display a please wait dialog for a long running operation. The problem is since this is single threaded even though I tell the WaitScreen to display it never

4条回答
  •  情深已故
    2020-12-13 12:21

    Doing it single threaded really is going to be a pain, and it'll never work as you'd like. The window will eventually go black in WPF, and the program will change to "Not Responding".

    I would recommending using a BackgroundWorker to do your long running task.

    It's not that complicated. Something like this would work.

    private void DoWork(object sender, DoWorkEventArgs e)
    {
        //Do the long running process
    }
    
    private void WorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        //Hide your wait dialog
    }
    
    private void StartWork()
    {
       //Show your wait dialog
       BackgroundWorker worker = new BackgroundWorker();
       worker.DoWork += DoWork;
       worker.RunWorkerCompleted += WorkerCompleted;
       worker.RunWorkerAsync();
    }
    

    You can then look at the ProgressChanged event to display a progress if you like (remember to set WorkerReportsProgress to true). You can also pass a parameter to RunWorkerAsync if your DoWork methods needs an object (available in e.Argument).

    This really is the simplest way, rather than trying to do it singled threaded.

提交回复
热议问题