开发者

In Silverlight, how to make program sleep without occupying thread

开发者 https://www.devze.com 2023-04-01 20:36 出处:网络
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?

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.


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();


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).

0

精彩评论

暂无评论...
验证码 换一张
取 消