Start, stop thread, how implement multithread C#

You're writing a application do something hard, your app UI was not responding when it's running... and you try multithreading...

So, how to implement it? and how to stop it? and... ;) how do i know it's stopped? the snippet below may help you to get the answer.

Below is a small help to implement multithread in C# - does not lock UI and synchronize to avoid recall thread that not complete yet ( ex.. when button clicked, thread run, the button disabled, till the thread complete then resume the button.)



using System.Threading;

class MyClass{
bool _isStop=false;
bool _isStopSuccess = false;
private void Button1_Click(){
try
{
if (_isStop == true)
{
Button1.Text = "Stop";
ThreadPool.QueueUserWorkItem(new WaitCallback(DoWork));
}
else
{
_isStop = true;
while (!_isStopSuccess)
Thread.Sleep(1000);
Button1.Text = "Start";
}

}
catch (Exception ex)
{
_isStop = true;
Button1.Text = "Start";
}
}


private void DoWork(object state)
{
// In this sample, our function must has a loop
// cuz we need to check the _isStop status every time the loop loops
// otherwise, we had to Abort the thread if we want to stop it.
for(int i=0;i<1000;i++)
{
if (_isStop)
{
_isStopSuccess = true;
return;
}

// your work here
// ..............
}
}
}// end class

You should do check variable "_isStop" often, so that the thread could return as soon as possible.
The idea "_isStopSuccess" to show our whether thread is stopped successful and we can do something to get a better app ;) ( may be change label of a button between "Do work" and "Working...", set enable some control ... )

In the case your thread function does not in a loop, so how to stop it? With .Net 2.0 and higher, we should use BackGroundWorker class to implement multithreading. It's also provided ways to stop thread easily. In this case, with .Net 1.1, we must call Abort from our Thread instance to abort it. And also remember to try catch it, cuz the ThreadAbortException will occurred when thread was aborted.

Hope this useful for you.
Happy harvest exp.

1 nhận xét:

Anonymous said...

Thanks and good idea to stop and start a thread..

Karthik

 

Coding experience share Copyright © 2010 | Designed by Ipietoon for Free Blogger Template