Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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:

Wait Timeouts

like image 864
garik Avatar asked Jul 13 '26 02:07

garik


2 Answers

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.

like image 109
i_am_jorf Avatar answered Jul 14 '26 17:07

i_am_jorf


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.

like image 37
Tim Avatar answered Jul 14 '26 16:07

Tim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!