0

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?

Yael
  • 1,566
  • 3
  • 18
  • 25
Taras
  • 1,118
  • 2
  • 12
  • 19

3 Answers3

4

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);
   }
});    
Bob Vale
  • 18,094
  • 1
  • 42
  • 49
0

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.

Bernhard Krenz
  • 279
  • 1
  • 4
0

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();
Terry Ma
  • 369
  • 1
  • 7