Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to abort a thread started inside another function?

Monitor moni = new Monitor();
Thread t = new Thread(() => moni.CurrUsage(nics,200));
t.Start();

I start a thread named 't' inside the 'Form1_Load' function. I have added a button. When click on that button the thread 't' should stop executing and create a new thread with these parameters.

Monitor moni = new Monitor();
Thread t = new Thread(() => moni.CurrUsage(nics,950));
t.Start();

I know in the form_load event i can use the

t.Abort();
like image 921
vishnu Avatar asked Dec 29 '22 05:12

vishnu


1 Answers

By making t a member of the form, you can reference it later on in the button-click event handler.

Graceful Abort. Although t.Abort() gets the job done, you might be left with half-processed data in the thread t. You can catch the ThreadAbortException in thread t to gracefully end processing.

Beware of overlap. The second problem is that your thread might not have aborted yet while your new thread has started already. You can prevent that by calling t.Join() after calling t.Abort().

Hope this helps.

like image 117
Joseph Tanenbaum Avatar answered Jan 11 '23 15:01

Joseph Tanenbaum