当前位置:网站首页>C# async and multithreading
C# async and multithreading
2022-08-03 05:05:00 【ViperL1】
一、异步
1.创建一个异步
//1-定义一个委托
public delegate int MyCal(int num);
//2-Implement methods based on delegates
private int ExecuteTask(int num)
{
Thread.Sleep(5000);
return num*num;
}
//3-调用方法
MyCal objCal = ExecuteTask; //Refer to the corresponding method
//1.通过委托调用BeginInvoke调用
IAsyncResult Reslut = objCal.BeginInvoke(10,null,null);
//输入和输出变量、回调函数、Figured out the parameters of the callbackobject;Returns the asynchronous operation state interface type
//2.获取异步执行结果
int r = objCal.EndInvoke(Reslut); //参数为:Asynchronous operation state interface type
2.Create multiple async
//1-定义一个委托
public delegate int MyCal(int num,int ms);
//2-Implement methods based on delegates
private int ExecuteTask(int num,int ms)
{
Thread.Sleep(ms);
return num*num;
}
//3-调用方法
MyCal objCal = ExecuteTask; //Refer to the corresponding method
//也可以使用 MyCal objCal = new MyObj(ExecuteTask);
//通过forThe loop can be called repeatedly
for(int i=1; i<11; i++)
{
objCal.BeginInvoke(10*i,1000*i,MyCallBack,i);
}
//4-重写回调函数
private MyCallBack(IAsyncResult reslut)
{
int res = objMyCal.EndInvoke(result);
ConSole.WirteLine("第"+result.AsyncState.ToString()+"The completion result is "+res);
}
①result.AsyncState的内容就是BeginInvoke中The content injected by the last parameter.
②The overridden callback function fires automatically when execution ends.
③BeginInvokeIt can be called cyclically to achieve the effect of multi-tasking
3.运用Lambda表达式/Anonymous delegation simplified
//1-定义一个委托
public delegate int MyCal(int num,int ms);
//2-使用匿名委托+Lambda表达式
this.objMyCal = (num,ms) =>
{
System.Threading.Thread.Sleep(ms);
return num*num;
}
4.Features of asynchronous programming
①建立在on a commissioned basis
②每个方法Runs independently in a thread
③More suitable for time-consuming“简单任务”,Ask for tasks directly相互独立,且Visual controls cannot be accessed directly
④Not suitable must be pressedexecute in a specific order/访问共享资源,可以选择多线程
二、多线程
1.suggested thread
1--建立线程
Thread objT1 = new Thread(Func1); //单参数方法:The method that needs to be called before use<无参委托>
//Or use anonymous delegate
Thread objT2 = new Tread(delegate()
{
//执行代码
});
2--设置后台线程
objT1.IsBackground = true; //设置为后台线程
3-启动线程
objT1.Start();
2.跨线程访问控件
一般情况下来说,C#Cross-threading is not allowed调用控件,可以采用以下方法解决
①Disable cross-thread checking
Control.CheckForIllegalCrossThreadCalls = false;
//在Load阶段注入,Turn off cross-thread checking
②使用Invoke方法
lblResult.Invoke(new Action<string>(s=>{ lblResult.Text = s}),a.ToString());
//The parameter is a no-return delegate
3.Read and manage processes
需要引入命名空间:System.Diagnostics;
句柄(Handle):进程的标识符;The handle needs to be removed after closing the process;handle can通过Process对象的Handle属性访问(Such as exit code、时间)
①Get the process used by the machine
private Process[] allProcess = null; //定义容器
allProcess = Process.GetProcess(); //Get all processes
②获取进程信息
Process CurrProcess = allProcess[x]; //Get a process
ProcessModuleCollection models = CurProcess.Modules; //Get the infoset of the modules called by the process
foreach(ProcessModule item in models)
{
lblShow.Text += item.FileName; //Display all module information
}
string info = CurrProcess.Id; //进程的ID
string info = CurrProcess.Handle; //进程句柄
string info = CurrProcess.HandleCount; //进程打开的句柄数
string info = CurrProcess.BasePriority; //进程的优先级
string info = CurrProcess.StartTime; //进程启动优先级
③进程管理
//立即关闭进程
CurProcess.Kill();
CurProcess.Close(); //释放进程资源
//开启一个进程
Process.Start(ProgramName); //参数为文件名(如edge.exe)
Process.Start("edge.exe"."www.baidu.com"); //The second parameter is the execution path
④线程安全
Uncertainty in multithreaded execution is possiblelead to competition for resources.可以采用加锁way to control it
//Lock the thread code--Make sure that the resources inside can only be called by the current code
lock(this)
{
//执行代码
}
//Use method attributes to implement locking
using System.Runtime.CompilerService; //Introduce system compilation service
//Add properties outside of multithreaded execution functions
[MethodImpl(MethondImplOptions.Synchronized)]
private void ActionMethod() {}
边栏推荐
- 多肽介导PEG磷脂——靶向功能材料之DSPE-PEG-RGD/TAT/NGR/APRPG
- Fluorescent marker peptides FITC/AMC/FAM/Rhodamine TAMRA/Cy3 / Cy5 / Cy7 - Peptide
- CobalStrike(CS)基础超级详细版
- redis键值出现 xacxedx00x05tx00&的解决方法
- WinForm的控件二次开发
- User password encryption tool
- 荧光标记多肽FITC/AMC/FAM/Rhodamine/TAMRA/Cy3/Cy5/Cy7-Peptide
- MySQL 入门:Case 语句很好用
- Harmony OS Date ano UI 】 【 】 the basic operation
- typescript43-类型兼容性说明
猜你喜欢
MCM箱模型建模方法及大气O3来源解析
传统企业如何转型社交电商,泰山众筹的玩法有哪些?
Detailed explanation of MOSN reverse channel
【Harmony OS】【ARK UI】轻量级数据存储
Secondary development of WinForm controls
私域流量时代来临,电商企业如何布局?
Redis缓存雪崩、缓存穿透、缓存击穿
MCM box model modeling method and source analysis of atmospheric O3
测试人员的价值体现在哪里
Common fluorescent dyes to modify a variety of groups and its excitation and emission wavelength data in the data
随机推荐
WebSocket的实际应用
三丁基-巯基膦烷「tBuBrettPhos Pd(allyl)」OTf),1798782-17-8
打破传统电商格局,新型社交电商到底有什么优点?
Two ways to simulate multi-user login in Jmeter
接口测试框架实战(二)| 接口请求断言
BIOTIN ALKYNE CAS: 773888-45-2 Price, Supplier
DFS对剪枝的补充
用户密码加密工具
[Harmony OS] [ArkUI] ets development graphics and animation drawing
Bubble sort in c language structure
【Harmony OS】【ARK UI】ets use startAbility or startAbilityForResult to invoke Ability
Shell条件语句判断
6.神经网络剖析
软件开发的最大的区别是什么?
C#异步和多线程
好消息!北京、珠海PMP考试时间来啦
【生物素叠氮化物|cas:908007-17-0】价格_厂家
数字孪生园区场景中的坐标知识
接口和协议
接口测试框架实战 | 流程封装与基于加密接口的测试用例设计