当前位置:网站首页>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() {}
边栏推荐
- Secondary development of WinForm controls
- 【开发者必看】【push kit】推送服务服务典型问题合集2
- Interface Test Framework Practice (4) | Get Schema Assertion
- 接口和协议
- Apache DolphinScheduler版本2.0.5分布式集群的安装
- Online password generator tool recommendation
- 10.预测房价:回归问题
- Two ways to simulate multi-user login in Jmeter
- Flink状态
- Redis缓存雪崩、缓存穿透、缓存击穿
猜你喜欢
Talking about GIS Data (6) - Projected Coordinate System
Interface test practice | Detailed explanation of the difference between GET / POST requests
typescript42-readonly修饰符
Shell conditional statement judgment
BIOTIN ALKYNE CAS: 773888-45-2 Price, Supplier
Common lipophilic cell membrane dyes DiO, Dil, DiR, Did spectrograms and experimental procedures
常见荧光染料修饰多种基团及其激发和发射波长数据一览数据
Bubble sort in c language structure
探索性测试的概念及方法
软件开发的最大的区别是什么?
随机推荐
rosbag工具plotjuggler无法打开rosbag的问题
Secondary development of WinForm controls
链动2+1模式简单,奖励结构丰厚,自主裂变?
GIS数据漫谈(五)— 地理坐标系统
【Harmony OS】【ARK UI】ets use startAbility or startAbilityForResult to invoke Ability
How to prepare for the test interface test data
shell script loop statement
2.何为张量
Harmony OS ets ArkUI 】 【 】 the development basic page layout and data connection
常见荧光染料修饰多种基团及其激发和发射波长数据一览数据
如何利用 Flutter 实现炫酷的 3D 卡片和帅气的 360° 展示效果
移动流量的爆发式增长,社交电商如何选择商业模式
typescript43-类型兼容性说明
Practical application of WebSocket
【Harmony OS】【FAQ】Hongmeng Questions Collection 1
Detailed explanation of MOSN reverse channel
8.电影评论分类:二分类问题
【Harmony OS】【ArkUI】ets开发 图形与动画绘制
Exception(异常) 和 Error(错误)区别解析
install ambari