C # how to stop a thread in time?

I have a user control that includes a timer. When a timer event fires, it invokes some threads.

User control

class MyControl { public Timer iTime { get; set; } Timer tmr; public MyControl { tmr = new Timer(); } // Some Properties } } 

Basic form

 class MyForm { Thread thd; MyControl cls = new MyClass(); cls.iTime.Tick += new EventHandler(iTime_Tick); void iTime_Tick(object sender, EventArgs e) { thd = new Thread(delegate() { doWork(1); }); thd.Start(); thd = new Thread(delegate() { doOtherJob(); }); thd.Start(); } delegate void notif(int Param1); void Job(int Param1) { if (this.InvokeRequired) { notif handler = new notif(notifParam); this.Invoke(handler, new object[] { Param1 }); } else { // Other Process } } private void Logout() { cls.iTime.Stop(); cls.iTime.Enabled = false; cls.iTime.Tick -= new EventHandler(iTime_Tick); thd.abort(); thd.join(); } } 

How to end a thread in a timer? When I turn off the timer event even in closed form, threads are still executing.

+4
source share
1 answer

Disposing a form does not affect your flows.

Your code is clearly incomplete (e.g. MyControl cls = new MyClass(); and we don’t know what doWork or doOtherJob ), but I suspect that part of the problem is that you have only one thread variable.

Each time the timer goes off, you do thd = new Thread twice. If your timer goes off ten times, then thd points to your last thread, but there are 19 other threads that are still running, and any of them can support your application.

One thing that can help is to explicitly set .IsBackground to true in the threads you create, as this will help to terminate them when your user interface thread closes. However, I would advise that creating this large number of threads in this way is most likely not an efficient model, and you'd better reconsider your design to run only one or two workflows instead of kicking dozens.

+2
source

Source: https://habr.com/ru/post/1502073/


All Articles