[2.0] Threading in C#.Net
Hello Guyz, :)
How are you all,Again i came with threading problem.please solve me.
I am using C#.net Windows application. my application frequently execute the one
funtion.so i need to go thread.The main thread just execute the thread and return back.when i close the application the main thread stop thread.that is procedure. so i write code like this.
Main thread start the thread
Code:
private void start()
{
object synobject = new object();
isthreadrunning = true;
Thread t = new Thread(new ThreadStart(startthread)
t.start()
}
Code:
private void startthread()
{
while(true)
{
lock(synobject)
{
if (isthreadrunning == false)
return;
}
Beginexecute()
Thread.sleep(1000);
}
}
Main thread stop the thread.
Code:
private void stop()
{
lock(synobject)
{
isthreadrunning == false;
}
t.abort();
}
When Main thread stop the thread..
i wont access the form. is completely blocked. is there any problem in above coding. Please solve this problem..
Thanks in Advance,
Dana
Re: [2.0] Threading in C#.Net
Instead of aborting the thread, let it complete naturally when you set the 'isthreadrunning' flag to false.
Try this, see if it works:
In the main thread:
Code:
private void stop()
{
isthreadrunning = false;
}
Code:
private void startthread()
{
while(isthreadrunning)
{
Beginexecute();
Thread.Sleep(1000);
}
}
Re: [2.0] Threading in C#.Net
If you're going to call the Abort method of a Thread then you are supposed to handle the ThreadAbortException that gets thrown as a result.
A better idea would be to either use a BackgroundWorker and call its CancelAsync method. Make sure that you read about that method first if you want to use it because there's more to it than just that.
There's another option too. If your worker thread can simply be terminated at any point without the need for cleanup, which it presumably can given what you're doing at the moment, then there's no need for you explicitly terminate the thread. Simply set its IsBackground property to True before you start it and then it will terminate on its own when you exit the app.