As a result of the project needs, the use of multithreaded solutions, where the main thread is responsible for interface processing (such as display data, and user interaction, etc.), child thread is responsible for reading and writing the serial port (send commands, read data). However, because of the less experience of using multithreading, some detours have been made on the issue of closing child threads, which Liu Wen in the hope of helping friends who have encountered this problem.
Version 1:
When the client closes the program, the main thread closes directly, regardless of the child thread.
Problem: In Task Manager, the main program process is still running (at the end of the child thread, and the child thread is made while (1). )
Version 2:
When the main thread closes processing, the child thread is first closed. The code is as follows:
///<summary>///Stop scanning threads///</summary>///<param name= "Messag" E "> Action module's prompt message </param> private void Stopscanthread () {cursor.current = Cursors.waitcu
Rsor;
if (this.tmCount.Enabled) {tmcount.enabled = false;
waitperiod = 0; } this.
Showstatus ("Closing scan port ..."); if (monitor!= null) {Monitor.
Closeserialport (); } if (workthread[1]!= null) {workthread[1].
Abort (); while (workthread[1).
ThreadState!= System.Threading.ThreadState.Stopped)//must wait for the thread to completely stop, otherwise there will be a conflict.
{Thread.Sleep (2000); }} this.
Showstatus ("Data collection stopped ...");
Cursor.current = Cursors.arrow; }
Problem: The main program does not shut down, similar to the panic.
Version 3: Improve and force the process to stop the same name when the program starts. Implemented in the main method of Program.cs, the code is as follows:
#region Kill the process that was not stopped because the software was last shut down (side effects of multithreading)
process[] processes = System.Diagnostics.Process.GetProcesses ();//Get All Processes
foreach (Process p in processes)
{
if (P.processname = = "Watermonitoris_weiding" && p.starttime < DateTime.Now.AddMinutes ( -2))
{
P.kill ();
}
#endregion
Version 4: (final version)
In C # multithreaded programming, the thread object has a IsBackground property, set to true, and the child thread closes when the main thread closes, fast.
Workthread.isbackground = true;