当其他线程开始做某事时,Wpf窗口会冻结

时间:2011-04-25 16:07:00

标签: c# wpf multithreading

WPF中有什么东西在WindowsForms中用“DoEvents”方法吗?

我问这个是因为我试图在一个线程中使用COM Interop,当它正在完成他的工作时,ProgressBar正在更新。

我找不到任何容易做到这一点的事情。

我没有太多时间阅读和实现一些疯狂的事情,我几乎要退出并将ProgressBar与Property IsIndeterminate保持为True。

1 个答案:

答案 0 :(得分:3)

以下示例向您展示了如何在除UI线程之外的另一个线程中执行某些操作。我不太了解COM,所以我不能说它如何与COM调用相结合,但对于.net方面,这应该可以帮助你而不需要阅读很多东西。 Here您找到了文档。

BackgroundWorker bgWorker = new BackgroundWorker() { WorkerReportsProgress=true};  
bgWorker.DoWork += (s, e) => {      

    // As your requested, here an example on how you yould instantiate your working class,
    //  registering to some progresse event and relay the progress to the backgorund-worker:

    YourClass workingInstance=new YourClass();
    workingInstance.WorkProgress+=(o,yourProgressEvent)=>{
       bgWorker.ReportProgress(yourProgressEvent.ProgressPercentage);
    };
    workingInstance.Execute();

};  
bgWorker.ProgressChanged+=(s,e)=>{      
    // Here you will be informed about progress and here it is save to change/show progress. 
    // You can access from here savely a ProgressBars or another control.  
};  
bgWorker.RunWorkerCompleted += (s, e) => {      
// Here you will be informed if the job is done. 
// Use this event to unlock your gui 
};  
bgWorker.RunWorkerAsync();  

虽然我不建议使用它,但这里有一个代码示例,可以从DoEvents中了解到这一点:

DispatcherFrame frame = new DispatcherFrame();
Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(delegate(object parameter) {
                frame.Continue = false;
                return null;
            }), null);
            Dispatcher.PushFrame(frame);