Restarting a thread in .NET (using C#)

c#, multithreading

Solution

Simply add `MyThread = new Thread(MyFunction)` before calling `MyThread.Start()` in `doStart()`. Do not create the thread outside of your methods, the space there is thought for declarations.

Please note that killing a thread with thread.Abort() can be very dangerous, as it might cause unexpected behavior or might not correctly dispose resources owned by the thread. You should try to accomplish clean multi threading, like Groo described in his answer.

Problem

I'm looking for a way to restart a thread that has been stopped by Abort().. ``` public partial class MyProgram : Form { private Thread MyThread = new Thread(MyFunction); private System.Windows.Forms.Button startStopBtn = new System.Windows.Forms.Button(); public MyProgram() { MyThread.Start(); startStopBtn += new EventHandler(doStop); startStopBtn.Text = "Stop"; } private static void MyFunction() { // do something } private void doStop(object sender, EventArgs e) { MyThread.Abort(); startStopBtn -= new EventHandler(doStop); startStopBtn += new EventHandler(doStart); startStopBtn.Text = "Start"; } private void doStart(object sender, EventArgs e) { MyThread.Start(); // << Error returned when clicking the button for 2nd time startStopBtn -= new EventHandler(doStart); startStopBtn += new EventHandler(doStop); startStopBtn.Text = "Stop"; } } ``` Any idea?

Original source

Related problems