Dispatcher.Invoke hangs main window

梦想与她 提交于 2020-01-06 07:43:51

问题


I've created new WPF project, in main window I'm doing:

public MainWindow()
{
    InitializeComponent();

    Thread Worker = new Thread(delegate(){

        this.Dispatcher.BeginInvoke(DispatcherPriority.SystemIdle, new Action(delegate
        {
            while (true)
            {
                System.Windows.MessageBox.Show("asd");

                Thread.Sleep(5000);
            }
        }));
    });

    Worker.Start();
}

the problem is between those messages MainWindow hangs. How do I get it work asynchronously?


回答1:


Because you are telling the UI thread to sleep and you are not letting the dispatcher return to processing its main message loop.

try something more like

Thread CurrentLogWorker = new Thread(delegate(){
   while (true) {
      this.Dispatcher.Invoke(
                 DispatcherPriority.SystemIdle, 
                 new Action(()=>System.Windows.MessageBox.Show("asd")));
      Thread.Sleep(5000);
   }
});    



回答2:


What do you try to archive?

Your while-Loop and the Thread.Sleep() are executed on the UI-Thread, so no wonder the MainWindow-hangs.

You should put these two outside the BeginInvoke-call and only the MessageBox.Show inside the Action.




回答3:


the delegate code you sent to Dispather.BeginInvoke is executed in main thread.
you should not sleep or do other long time job in the delegate of BeginInvoke method.

you should do long time job before BeginInovke method like this.

Thread CurrentLogWorker = new Thread(delegate(){
    while (true)
    {
        this.Dispatcher.Invoke(DispatcherPriority.SystemIdle, new Action(delegate
        {
            System.Windows.MessageBox.Show("asd");
        }));

        Thread.Sleep(5000);
    }
});
CurrentLogWorker.Start();


来源:https://stackoverflow.com/questions/16298600/dispatcher-invoke-hangs-main-window

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!