Option 1:
Call the thread control method. Start:Thread.Start();Stop:Thread. Abort();Pause:Thread.Suspend();Continue:Thread.Resume();
private void btn_Start_Click(object sender, EventArgs e) { mThread.Start(); // 开始 }private void btn_Stop_Click(object sender, EventArgs e) { mThread.Abort(); // 终止 }private void btn_Suspend_Click(object sender, EventArgs e) { mThread.Suspend(); // 暂停 }private void btn_Resume_Click(object sender, EventArgs e) { mThread.Resume(); // 继续}
The thread is defined as:
mThread = new Thread(() =>{try{for (int j = 0; j ";for (int i = 0; i vSum = {1}\r\n", DateTime.Now.ToString(), vSum); Thread.Sleep(1000); } }catch (ThreadAbortException ex) { Console.WriteLine("ThreadAbortException:{0}", ex.Message); } });
It is worth noting: Threads that are stopped by Thread.Abort() (or end by themselves) thread), cannot be started again directly through the Thread.Start() method, and a thread must be re-created to start.
So, the "Start Button" event should be:
private void btn_Start_Click(object sender, EventArgs e) {// 定义线程mThread = new Thread(() => // Lambda 表达式 {try{for (int j = 0; j ";for (int i = 0; i vSum = {1}\r\n", DateTime.Now.ToString(), vSum); Thread.Sleep(1000); } }catch (ThreadAbortException ex) { Console.WriteLine("ThreadAbortException:{0}", ex.Message); } }); mThread.Start(); // 开始}
In addition, for the Thread.Suspend() and Thread.Resume() methods, Microsoft has marked them Deprecated:
#Thread.Suspend has been deprecated. Please use other classes in System.Threading, such as Monitor, Mutex, Event, and Semaphore, to synchronize Threads or protect resources. (Thread.Suspend has been deprecated. Please use other thread classes in the system, such as monitors, mutexes, events, and semaphores, to synchronize threads or protect resources.)Because it is impossible to determine what code the thread is executing when it is currently suspended. If the thread holding the lock is suspended during security permissions evaluation, other threads in the AppDoamin may be blocked. If you suspend a thread while it is executing the constructor, other threads in the AppDomain that try to use the class will be blocked. This is prone to deadlock.
Option 2: Determine whether to continue at an appropriate position during the thread running process (such as after a complete function/command) thread, and then determine the fate of the thread.
1. Define a global variable:
int
mTdFlag = 0; // 1: Normal operation; 2: Pause; 3: Stop 2. Define a judgment method:
bool WaitForContinue() {if (this.mTdFlag == 3) {return false; // 返回false,线程停止 }else if (this.mTdFlag == 2) {while (mTdFlag != 1) { Thread.Sleep(200); // 假暂停;停顿时间越短,越灵敏if (this.mTdFlag == 3) {return false; // 返回false,线程停止 } } }return true; // 返回true,线程继续}
private void btn_Stop_Click(object sender, EventArgs e) {this.mTdFlag = 3;//mThread.Abort(); // 终止 }private void btn_Suspend_Click(object sender, EventArgs e) {this.mTdFlag = 2;//mThread.Suspend(); // 暂停 }private void btn_Resume_Click(object sender, EventArgs e) {this.mTdFlag = 1;//mThread.Resume(); // 继续}
mThread = new Thread(() =>{try{for (int j = 0; j ";for (int i = 0; i vSum = {1}\r\n", DateTime.Now.ToString(), vSum);if (!WaitForContinue()) // 返回 false 则,停止 {break;// return; } Thread.Sleep(1000); } }catch (ThreadAbortException ex) { Console.WriteLine("ThreadAbortException:{0}", ex.Message);this.textBox1.Text += ex.Message + "..."; }finally{this.textBox1.Text += "线程已结束"; } });
In the form, solve the problem of cross-thread access:
In the form constructor Add code: Control.CheckForIllegalCrossThreadCalls = false;[]
The above is the detailed content of Detailed explanation of examples of C# thread control. For more information, please follow other related articles on the PHP Chinese website!

Design patterns in C#.NET include Singleton patterns and dependency injection. 1.Singleton mode ensures that there is only one instance of the class, which is suitable for scenarios where global access points are required, but attention should be paid to thread safety and abuse issues. 2. Dependency injection improves code flexibility and testability by injecting dependencies. It is often used for constructor injection, but it is necessary to avoid excessive use to increase complexity.

C#.NET is widely used in the modern world in the fields of game development, financial services, the Internet of Things and cloud computing. 1) In game development, use C# to program through the Unity engine. 2) In the field of financial services, C#.NET is used to develop high-performance trading systems and data analysis tools. 3) In terms of IoT and cloud computing, C#.NET provides support through Azure services to develop device control logic and data processing.

.NETFrameworkisWindows-centric,while.NETCore/5/6supportscross-platformdevelopment.1).NETFramework,since2002,isidealforWindowsapplicationsbutlimitedincross-platformcapabilities.2).NETCore,from2016,anditsevolutions(.NET5/6)offerbetterperformance,cross-

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.

C# is not always tied to .NET. 1) C# can run in the Mono runtime environment and is suitable for Linux and macOS. 2) In the Unity game engine, C# is used for scripting and does not rely on the .NET framework. 3) C# can also be used for embedded system development, such as .NETMicroFramework.

C# plays a core role in the .NET ecosystem and is the preferred language for developers. 1) C# provides efficient and easy-to-use programming methods, combining the advantages of C, C and Java. 2) Execute through .NET runtime (CLR) to ensure efficient cross-platform operation. 3) C# supports basic to advanced usage, such as LINQ and asynchronous programming. 4) Optimization and best practices include using StringBuilder and asynchronous programming to improve performance and maintainability.

C# is a programming language released by Microsoft in 2000, aiming to combine the power of C and the simplicity of Java. 1.C# is a type-safe, object-oriented programming language that supports encapsulation, inheritance and polymorphism. 2. The compilation process of C# converts the code into an intermediate language (IL), and then compiles it into machine code execution in the .NET runtime environment (CLR). 3. The basic usage of C# includes variable declarations, control flows and function definitions, while advanced usages cover asynchronous programming, LINQ and delegates, etc. 4. Common errors include type mismatch and null reference exceptions, which can be debugged through debugger, exception handling and logging. 5. Performance optimization suggestions include the use of LINQ, asynchronous programming, and improving code readability.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version
SublimeText3 Linux latest version

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version
Visual web development tools
