当前位置:网站首页>C # [advanced part] C # multithreading
C # [advanced part] C # multithreading
2022-06-30 03:21:00 【Tomorrow is like noon】
C#【 Advanced 】 C# Multithreading
Preface
Threads Defined as the execution path of a program . Each thread defines a unique control flow . If your application involves complex and time-consuming operations , It is often beneficial to set different thread execution paths , Each thread performs a specific job .
Threads are lightweight processes . A common example of using threads is in modern operating systems Implementation of parallel programming . Use Thread savings CPU Waste of cycles , At the same time, it improves the efficiency of the application .
So far, the program we've written is a single thread running as a single process of the running instance of the application . however , This way, the subapplication can only perform one task at a time . In order to perform multiple tasks at the same time , It can be divided into smaller threads .
One 、 Thread life cycle
The thread life cycle starts at System.Threading.Thread When an object of class is created , End when the thread is terminated or finished executing .
The various states in the thread life cycle are listed below :
Not started : When a thread instance is created but Start State when method is not called .
Ready state : When the thread is ready to run and wait CPU The condition of a cycle .
Non operational state : Threads are not runnable in the following cases :
Has called Sleep Method
Has called Wait Method
adopt I/O Operation blockingDeath state : The condition when a thread has completed execution or has been aborted .
Two 、 The main thread
stay C# in ,System.Threading.Thread Class is used for the work of threads . It allows you to create and access a single thread in a multithreaded application . The first thread executed in a process is called the primary thread .
When C# At the beginning of the program , The main thread is created automatically . Use Thread Class is called by a child thread of the main thread . You can Use Thread Class CurrentThread Property access thread .
The following program demonstrates the execution of the main thread :
using System;
using System.Threading;
namespace MultithreadingApplication
{
class MainThreadProgram
{
static void Main(string[] args)
{
Thread th = Thread.CurrentThread;
th.Name = "MainThread";
Console.WriteLine("This is {0}", th.Name);
Console.ReadKey();
}
}
}
Running results :
This is MainThread
3、 ... and 、 Create thread
Threads are through extensions Thread Class created . Extended Thread Class call Start() Method to start the execution of the child thread .
The following program demonstrates this concept :
using System;
using System.Threading;
namespace MultithreadingApplication
{
class ThreadCreationProgram
{
public static void CallToChildThread()
{
Console.WriteLine("Child thread starts");
}
static void Main(string[] args)
{
//【 How to write it 1】:ThreadStart、Thread All use
ThreadStart childref = new ThreadStart(CallToChildThread);
Console.WriteLine("In Main: Creating the Child thread");
Thread childThread = new Thread(childref);
//【 How to write it 2】 Use only Thread. stay 2.0 In the future, it can be written like the following , The program will be easier to understand
//Thread childThread = new Thread(CallToChildThread);
childThread.Start();
Console.ReadKey();
}
}
}
Running results :
In Main: Creating the Child thread
Child thread starts
In particular :
The effect of the two writing methods below is the same . Is to create a thread . The latter is just C# The grammar of , The compiler will automatically convert to the first form at compile time .ThreadStart Is the entry to the thread , It can be understood as a function pointer , Point to the function that the thread will run .
Thread childThread = new Thread( new ThreadStart(CallToChildThread));
Thread childThread = new Thread(CallToChildThread);
Four 、 Manage threads 【Thread.Sleep(1000) Thread pause 1s】
Thread Class provides various methods for managing threads .
The following example demonstrates sleep() Use of methods , Used to pause a thread at a specific time .
using System;
using System.Threading;
namespace MultithreadingApplication
{
class ThreadCreationProgram
{
public static void CallToChildThread()
{
Console.WriteLine("Child thread starts");
// Thread pause 5000 millisecond
int sleepfor = 5000;
Console.WriteLine("Child Thread Paused for {0} seconds",
sleepfor / 1000);
Thread.Sleep(sleepfor);
Console.WriteLine("Child thread resumes");
}
static void Main(string[] args)
{
ThreadStart childref = new ThreadStart(CallToChildThread);
Console.WriteLine("In Main: Creating the Child thread");
Thread childThread = new Thread(childref);
childThread.Start();
Console.ReadKey();
}
}
}
Running results :
In Main: Creating the Child thread
Child thread starts
Child Thread Paused for 5 seconds
Child thread resumes
5、 ... and 、 Destruction of the thread 【Abort()】
Abort() Method Used to destroy threads .
By throwing threadabortexception Abort thread at run time . This exception cannot be caught , If there is finally block , Control will be sent to finally block .
The following procedure illustrates this :
using System;
using System.Threading;
namespace MultithreadingApplication
{
class ThreadCreationProgram
{
public static void CallToChildThread()
{
try
{
Console.WriteLine("Child thread starts");
// Count to 10
for (int counter = 0; counter <= 10; counter++)
{
Thread.Sleep(500);
Console.WriteLine(counter);
}
Console.WriteLine("Child Thread Completed");
}
catch (ThreadAbortException e)
{
Console.WriteLine("Thread Abort Exception");
}
finally
{
Console.WriteLine("Couldn't catch the Thread Exception");
}
}
static void Main(string[] args)
{
ThreadStart childref = new ThreadStart(CallToChildThread);
Console.WriteLine("In Main: Creating the Child thread");
Thread childThread = new Thread(childref);
childThread.Start();
// Stop the main thread for a while
Thread.Sleep(2000);
// Now abort the child thread
Console.WriteLine("In Main: Aborting the Child thread");
childThread.Abort();
Console.ReadKey();
}
}
}
When the above code is compiled and executed , It will produce the following results :
In Main: Creating the Child thread
Child thread starts
0
1
2
In Main: Aborting the Child thread
Thread Abort Exception
Couldn't catch the Thread Exception
summary
- Process and thread understanding : process ( A program )、 Threads ( When concurrent, multiple branch programs )、 The main thread (Main)
- Common use of multithreading :Sleep、Abort、Resume
- Thread pool and Task Simple understanding
Add 1【Thread、 Thread pool ThreadPool、Task】
C# 4.0 In the future, there will be 3 Ways to create threads :
- ==Thread == Create your own independent thread , High priority , It needs to be managed by the user .
- ==ThreadPool == Yes .Net Manage yourself , Just write down the methods you need to deal with , Then hand it in. .Net Framework, As long as the subsequent method is executed , Will automatically exit .
- Task 4.0 New thread operation modes in the future , similar ThreadPool, But the efficiency test is better than ThreadPool Slightly higher , Task Support for multi-core is more obvious , So in a multi-core processor , Task The advantage is more obvious .
example :
using System;
using System.Threading;
namespace ConsoleApp2
{
class Program
{
public static Thread t =null;
static void Main(string[] args)
{
//【01】 Thread creation is independent
t = new Thread(ThreadProcess1);
t.Start(new object());
//【02】 Thread pool
ThreadPool.QueueUserWorkItem(ThreadProcess2, new object());
//【03】Task Method to create a thread
System.Threading.Tasks.Task.Factory.StartNew(ThreadProcess3, new object());
Console.ReadLine();
}
private static void ThreadProcess1(object tag)
{
int i = 10;
while (i > 0)
{
Console.WriteLine(string.Format("【01】i:{0} ", i));
Thread.Sleep(10);
i--;
}
Console.WriteLine("【01】 Thread end ");
// Manual termination required
t.Abort();
}
private static void ThreadProcess2(object tag)
{
int i = 10;
while (i > 0)
{
Console.WriteLine(string.Format("【02】i:{0} ", i));
Thread.Sleep(10);
i--;
}
Console.WriteLine("【02】 Thread end ");
}
private static void ThreadProcess3(object tag)
{
int i = 10;
while (i > 0)
{
Console.WriteLine(string.Format("【03】i:{0} ", i));
Thread.Sleep(10);
i--;
}
Console.WriteLine("【03】 Thread end ");
}
}
}
Running results :
Add 2【ThreadStart and ParameterizedThreadStart】
Thread functions are passed through delegates , No parameters , You can also take parameters ( There can only be one parameter ), You can encapsulate parameters with a class or structure :
using System;
using System.Threading;
namespace Test
{
class Program
{
static void Main(string[] args)
{
Thread t1 = new Thread(new ThreadStart(TestMethod));
Thread t2 = new Thread(new ParameterizedThreadStart(TestMethod));
t1.IsBackground = true;
t2.IsBackground = true;
t1.Start();
t2.Start("hello");
Console.ReadKey();
}
public static void TestMethod()
{
Console.WriteLine(" Thread functions without parameters ");
}
public static void TestMethod(object data)
{
string datastr = data as string;
Console.WriteLine(" Thread function with parameters , Parameter is :{0}", datastr);
}
}
}
Running results :
Thread functions without parameters
Thread function with parameters , Parameter is :hello
边栏推荐
猜你喜欢

1148_ Makefile learning_ Targets, variables, and wildcards in makefile

QT中foreach的使用

QT中foreach的使用

TiDB 6.0:让 TSO 更高效丨TiDB Book Rush

O & M (21) make winpe startup USB flash disk

X Book 6.97 shield unidbg calling method

Redis在windows系统中使用

Auto. JS learning notes 16: save to the mobile phone by project, instead of saving a single JS file every time, which is convenient for debugging and packaging

Learning cyclic redundancy CRC check

Hudi record
随机推荐
Mathematical solution of Joseph Ring
unity input system 使用记录(实例版)
prompt learning 一个空格引发的血案
O & M (21) make winpe startup USB flash disk
炒现货黄金的交易平台如何保障资金安全?
The broadcast module code runs normally in autojs4.1.1, but an error is reported in pro7.0 (not resolved)
Redis在windows系统中使用
Auto.js学习笔记16:按项目保存到手机上,不用每次都保存单个js文件,方便调试和打包
Shell counts all strings before the last occurrence of a string
shell统计某个字符串最后一次出现的位置之前的所有字符串
1150_ Makefile learning_ Duplicate name target processing in makefile
mysql 主从数据库同步失败的原因
Some technology sharing
Huawei interview question: divide candy
If you can tell whether the external stock index futures trading platform I am trading is formal and safe?
WPF Initialized事件在.cs中绑定不被触发的原因
2022 tool fitter (Advanced) and tool fitter (Advanced) certificate examination
什么是外链和内链?
编译一个无导入表的DLL
Servlet interview questions