Reputation: 2809
Thread.Suspend()
method is obsolete as you know. I want to suspend thread immidiately when button click event comes. I used Thread.Suspend() and it works perfect but everyone suggest that using Thread.Suspend() method is not a good method to suspend the task. I used a flag to suspend the task but every time when a button click event comes, i have to wait to exit from task. I used Thread.IsAlive flag to wait the thread to exit but this method freezes form.
void ButtonClickEvent(object sender, ButtonClickEventArgs e)
{
TheadExitFlag = false;
if(MyThread != null)
{
while(MyThread.IsAlive);
//MyThread.Suspend();
}
}
void MyTask(void)
{
while(TheadExitFlag)
{
// some process
Thread.Sleep(5000);
}
}
How can i suspend the thread immidiately?
Upvotes: 3
Views: 4082
Reputation: 2149
There is an approximate solution to this problem at https://stackoverflow.com/a/45786529/3013473 using AspectJ and wait/notify.
Upvotes: 0
Reputation: 48949
Use a ManualResetEvent
to toggle between a running and idle state.
ManualResetEvent run = new ManualResetEvent(true);
void ResumeButton_Click(object sender, ButtonClickEventArgs e)
{
run.Set();
PauseButton.Enabled = true;
ResumeButton.Enabled = false;
}
void PauseButton_Click(object sender, ButtonClickEventArgs e)
{
run.Reset();
PauseButton.Enabled = false;
ResumeButton.Enabled = true;
}
void MyTask(void)
{
while (run.WaitOne()) // Wait for the run signal.
{
// Do work here.
}
}
Upvotes: 4
Reputation: 24847
There is no alternative with the same functionality, AFAIK. I am not sure if the problems with an OS Suspend()
could be worked around within the language/libraries, but no attempt has been made to do so, so maybe it's too difficult or even sensibly impossible.
Until such an alernative exists, you are reduced to polling for a suspend flag and then waiting on some synchronization object for a 'resume' signal. I have used AutoResetEvent for this.
Upvotes: 4