当前位置:网站首页>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
- WinForm的控件二次开发
- Common fluorescent dyes to modify a variety of groups and its excitation and emission wavelength data in the data
- 移动流量的爆发式增长,社交电商如何选择商业模式
- Where is the value of testers
- c语言结构体中的冒泡排序
- 【生物素叠氮化物|cas:908007-17-0】价格_厂家
- typescript42-readonly修饰符
- MCM箱模型建模方法及大气O3来源解析
- Bubble sort in c language structure
猜你喜欢
Alienware上线首个数字时装AR试穿体验
UV 裂解的生物素-PEG2-叠氮|CAS:1192802-98-4生物素接头
How to prepare for the test interface test data
typescript41-class类的私有修饰符
Harmony OS Date ano UI 】 【 】 the basic operation
UV decomposition of biotin - PEG2 - azide | CAS: 1192802-98-4 biotin connectors
三丁基-巯基膦烷「tBuBrettPhos Pd(allyl)」OTf),1798782-17-8
typescript39-class类的可见修饰符
私域流量时代来临,电商企业如何布局?
Super handy drawing tool is recommended
随机推荐
接口测试 Mock 实战(二) | 结合 jq 完成批量化的手工 Mock
社交电商:流量红利已尽,裂变营销是最低成本的获客之道
超好用的画图工具推荐
Shell之条件语句
【Harmony OS】【ARK UI】ets使用startAbility或startAbilityForResult方式调起Ability
typescript39-class类的可见修饰符
MCM box model modeling method and source analysis of atmospheric O3
Redis缓存雪崩、缓存穿透、缓存击穿
DDL操作数据库、表、列
【生物素叠氮化物|cas:908007-17-0】价格_厂家
接口管理工具YApi怎么用?颜值高、易管理、超好用
User password encryption tool
typescript40-class类的保护修饰符
1.一个神经网络示例
【软件工程之美 - 专栏笔记】35 | 版本发布:软件上线只是新的开始
【Harmony OS】【FAQ】Hongmeng Questions Collection 1
Bubble sort in c language structure
BIOTIN ALKYNE CAS: 773888-45-2 Price, Supplier
shell脚本循环语句
接口测试框架实战(一) | Requests 与接口请求构造