当前位置:网站首页>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 type2.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 delegate3.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() {}边栏推荐
猜你喜欢

10.预测房价:回归问题

Apache DolphinScheduler版本2.0.5分布式集群的安装

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

MySql 创建索引

Super handy drawing tool is recommended

2022/08/02 学习笔记 (day22) 多线程

【HMS core】【Ads Kit】华为广告——海外应用在国内测试正式广告无法展示
随机推荐
传统企业如何转型社交电商,泰山众筹的玩法有哪些?
Talking about GIS Data (6) - Projected Coordinate System
typescript42-readonly修饰符
Talking about GIS Data (5) - Geographic Coordinate System
用户密码验证
MCM箱模型建模方法及大气O3来源解析
4.深度学习的几何解释与梯度的优化
MySql 创建索引
How to prepare for the test interface test data
2022/08/02 学习笔记 (day22) 多线程
typescript47-函数之间的类型兼容性
【Harmony OS】【ARK UI】ETS 上下文基本操作
GIS数据漫谈(五)— 地理坐标系统
rosbag工具plotjuggler无法打开rosbag的问题
Redis缓存雪崩、缓存穿透、缓存击穿
CAD有生僻字如何打出来、如何提交软件相关问题或建议?
社交电商如何做粉丝运营?云平台怎么选择商业模式?
好消息!北京、珠海PMP考试时间来啦
Super handy drawing tool is recommended
表的创建、修改与删除