当前位置:网站首页>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() {}
边栏推荐
- 【生物素叠氮化物|cas:908007-17-0】价格_厂家
- typescript44-对象之间的类兼容器
- Interface test Mock combat (2) | Combined with jq to complete batch manual Mock
- 2022/08/02 Study Notes (day22) Multithreading
- 【HMS core】【Ads Kit】Huawei Advertising——Overseas applications are tested in China. Official advertisements cannot be displayed
- c语言结构体中的冒泡排序
- 13.机器学习基础:数据预处理与特征工程
- IO进程线程->线程->day5
- IO process thread -> thread -> day5
- CobalStrike(CS)基础超级详细版
猜你喜欢
随机推荐
技术分享 | 接口自动化测试中如何对xml 格式做断言验证?
5.回顾简单的神经网络
Interface testing framework of actual combat (2) | interface request assertion
MySQL 入门:Case 语句很好用
Shell之条件语句
【Harmony OS】【ArkUI】ets开发 基础页面布局与数据连接
内部类、static关键字、final
三丁基-巯基膦烷「tBuBrettPhos Pd(allyl)」OTf),1798782-17-8
【Harmony OS】【ARK UI】轻量级数据存储
typescript43-类型兼容性说明
MySql 创建索引
typescript44-对象之间的类兼容器
【Harmony OS】【ARK UI】ETS 上下文基本操作
【Harmony OS】【FAQ】Hongmeng Questions Collection 1
js中的闭包
如何利用 Flutter 实现炫酷的 3D 卡片和帅气的 360° 展示效果
GIS数据漫谈(五)— 地理坐标系统
typescript45-接口之间的兼容性
OSI的分层特点、传输过程与三次握手、四次挥手、tcp与udp包头的描述
Flink状态