Hi!
Please consult me on the following question:
1. There is main GUI thread, two buttons Start and ReStart
2. ManualResetEvent is used to stop the working thread
3. "Start" creates and starts the thread
{
workThread = new Thread(() => DoWork());
workThread.Start();
}
void DoWork()
{
while (true)
{
Thread.Sleep(1000);
MethodInvoker methodInvoker = delegate() { "Update GUI" };
this.Invoke(methodInvoker);
if (manualResetEvent.WaitOne(0))
{
break;
}
}
}
4. ReStart should stop the thread and start new one with the same DoWork method.
My question is how correctly stop current thread and start new one?
{
manualResetEvent.Set();
//Incorrect because first thread can be still alive
workThread = new Thread(() => DoWork());
workThread.Start();
}
{
manualResetEvent.Set();
//Incorrect because there will be a deadlock on GUI thread
workThread.Join();
workThread = new Thread(() => DoWork());
workThread.Start();
}
Please advice correct implementation (maybe using tasks or other stuff from TPL)
Thank you
Please consult me on the following question:
1. There is main GUI thread, two buttons Start and ReStart
2. ManualResetEvent is used to stop the working thread
3. "Start" creates and starts the thread
{
workThread = new Thread(() => DoWork());
workThread.Start();
}
void DoWork()
{
while (true)
{
Thread.Sleep(1000);
MethodInvoker methodInvoker = delegate() { "Update GUI" };
this.Invoke(methodInvoker);
if (manualResetEvent.WaitOne(0))
{
break;
}
}
}
4. ReStart should stop the thread and start new one with the same DoWork method.
My question is how correctly stop current thread and start new one?
{
manualResetEvent.Set();
//Incorrect because first thread can be still alive
workThread = new Thread(() => DoWork());
workThread.Start();
}
{
manualResetEvent.Set();
//Incorrect because there will be a deadlock on GUI thread
workThread.Join();
workThread = new Thread(() => DoWork());
workThread.Start();
}
Please advice correct implementation (maybe using tasks or other stuff from TPL)
Thank you
Alexander