开发者

What code is better to delay main thread while working thread is doing its work

开发者 https://www.devze.com 2023-04-03 17:33 出处:网络
What code is better to delay (wait) main thread while working thread doing its work? 1) int ticks = System.Environment.TickCount;

What code is better to delay (wait) main thread while working thread doing its work?

1)

int ticks = System.Environment.TickCount;
while (System.Environment.TickCount - ticks < milliseconds);

2)

Thread.Sleep(milliseconds);

3)

Your variant.

Thank you.

ADDED

SOLUTION:

开发者_如何学GoWait Timeouts


Neither of those things are good. Either one will cause the UI to become unresponsive while the worker thread is doing its work.

Instead you should schedule work items to run on the worker thread, then send a message back to the UI thread when the work has completed.

One way of running things on the UI thread from the worker thread is:

Deployment.Current.Dispatcher.BeginInvoke(() =>
{
   // Your UI thread code to run here.
}

See also.

You can also use background workers.


Take a look at this: http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.onrunworkercompleted.aspx

This should do everything you need, assuming you are using the background worker class. As stated in another answer, the solutions you provided will really bog down your program, defeating the point of having another thread.


You can await your background operation to asynchronously wait until it completes. I don't recommend polling for it to complete by blocking for a time period.

await is supplied by the Async CTP, which is not finalized yet but generally believed to be included in Visual Studio vNext. In particular, the Async CTP does not work on Silverlight 5 RC (though Silverlight 4 does work).


I have not found valid answer, so decided to investigate this problem more deeply. Here is code that does not use Thread.Sleep:

    public void SetReady()
    {
        lock (syncObj)
        {
            ready = true;
            Monitor.Pulse(syncObj);
        }

    }


        public void Wait()
        {
            lock (syncObj)
            {
                while (!ready)
                {
                    Monitor.Wait(syncObj);
                }
            }
        }

See for more details: Wait Timeouts

0

精彩评论

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