当前位置:网站首页>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
边栏推荐
猜你喜欢

编译一个无导入表的DLL
![[wechat applet] how did the conditional rendering list render work?](/img/db/4e79279272b75759cdc8d6f31950f1.png)
[wechat applet] how did the conditional rendering list render work?

Implementation of property management system with ssm+ wechat applet

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

Stc89c52/90c516rd/89c516rd ADC0832 ADC driver code

QT中foreach的使用

On the optimization and use of idea

X书6.89版本shield-unidbg调用方式

Auto.js学习笔记16:按项目保存到手机上,不用每次都保存单个js文件,方便调试和打包

unity input system 使用记录(实例版)
随机推荐
Some technology sharing
1151_ Makefile learning_ Static matching pattern rules in makefile
自定义MVC的使用
2022 underground coal mine electrical test and underground coal mine electrical simulation test
Gulang bilibilibili Live Screen Jackie
Summary of PHP test sites encountered in CTF questions (I)
WPF initialized event in The reason why binding is not triggered in CS
[ten minutes] manim installation 2022
Implementation of property management system with ssm+ wechat applet
golang bilibili直播弹幕姬
【十分钟】manim安装 2022
MySQL + JSON = King fried
F1C100S自制开发板调试过程
专升本高数(三)
If you can tell whether the external stock index futures trading platform I am trading is formal and safe?
发现mariadb数据库时间晚了12个小时
A GPU approach to particle physics
快速排序、聚簇索引、尋找數據中第k大的值
Mysql提取表字段中的字符串
Golang BiliBili live broadcast bullet screen