1

I have been working with WPF and threading.

I would like to pause the whole screen (the application only) during a for loop.

E.g.

foreach (classA a in classesA)
{
....
....
Thread.sleep(100);

}

However, I found that it will sleep for long and then execute all the statement in a time. It is not what I want. I want to sleep within the execution of the for loop. That is to sleep 100ms after 1st loop, then sleep again after the 2nd loop.....

I found that some article mentioned DoEvents(), but I am not quite familiar with it and WPF seem don't have this kind of thing.

Some other articles mentioned DispatcherTimer. Still, it will not lock the screen. I would like to lock the whole screen (the application only) to prevent from clicking any button during the execution of the for loop.

How could I do so?

Thank you so much!

user883434
  • 717
  • 2
  • 10
  • 25

2 Answers2

4

You must not block the UI-thread otherwise it cannot process its queue, which contains rendering the UI, if you want to block interaction with UI-elements set IsEnabled=false on a root element, then to do a non-blocking wait see this question.

Community
  • 1
  • 1
H.B.
  • 166,899
  • 29
  • 327
  • 400
  • I have tried to make the Page IsEnabled=false. However, it turns some of my control from black to white, so ugly!! how to solve it? – user883434 Nov 10 '11 at 11:33
  • @user883434: You'd have to modify the template, if they were black to begin with someone did not properly style the state when they are disabled... – H.B. Nov 10 '11 at 11:53
  • An alternative is to set `IsHitTestVisible` to False if you don't like the look of disabled controls. This makes elements ignore clicks. – Aphex Nov 14 '11 at 21:31
0

If you are willing to experiment to with the proposed async and await keywords you could achieve the sleep behavior with synchronous semantics like this. You would need to install the Async CTP to do it though.1

public aysnc void YourButton_Click(object sender, EventArgs args)
{
  foreach (classA a in classes)
  {
    await Task.Delay(100);
  }
}

1The Async CTP uses TaskEx instead of Task.

Brian Gideon
  • 47,849
  • 13
  • 107
  • 150