2

I have a case that need embed a background sleep in a for loop. is there any way to do it without breakout the shape of for loop?

for (;;)
{
    Dosomething();
    Thread.Sleep(5000); // this blocks the UI thread, hope to find someway to sleep in background
}

-------------edited--------------

in Dosomething(), there is some UI thread operations like listBoxA.width += 5 (without dispatcher); Here the UI doesn't refresh until all the loop finishes. the reason I want to use Sleep is I want to see the UI refresh each Dosomething is executed, like a animation.

demaxSH
  • 1,743
  • 2
  • 20
  • 27
  • 1
    You should explain more what you want to achieve - are you doing a polling or messaging loop? You could run the whole loop on a background thread, but there is no purpose or logic to a background sleep in a foreground (UI) thread. – slugster Sep 01 '11 at 03:52
  • See this thread: http://stackoverflow.com/questions/2307929/what-is-the-c-equivalent-of-msgwaitformultipleobjects – i_am_jorf Sep 01 '11 at 03:53

2 Answers2

2

You did not provide much info for what you need your code, so I'll give it a try with this:

        int counter = 4;
        DispatcherTimer _timer = new DispatcherTimer();
        _timer.Interval = TimeSpan.FromSeconds(5);
        _timer.Tick += (s, e) =>
        {
            DoSomething();

            counter--;

            if (counter == 0) _timer.Stop();

        };
        _timer.Start();
Rumplin
  • 2,703
  • 21
  • 45
  • +1 although since the loop in the question is infinite I would not have included the counter here would make this code example much simpler. – AnthonyWJones Sep 01 '11 at 08:24
  • @Rumplin, as I edited on my thread, actually I am trying to do some UI operation in Dosomething(), and use the for loop to achieve animation effect. anyway I managed to do this using the time ticker. – demaxSH Sep 01 '11 at 17:17
0

Everything in Silverlight should be designed to run asynchronously. Your example is simply not the way to run regular background tasks in Silverlight (which is presumably is what your want DoSomething() to do).

Try reading up on BackgroundWorker to run your tasks on another thread generally and DispatchTimer to run regular tasks (as Rumplin suggested in his example).

iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202