委托笔记
action.BeginInvoke
public class Program
{
static void Main(string[] args)
{
Console.WriteLine($"********************* 系统开始 线程ID:{Thread.CurrentThread.ManagedThreadId.ToString("00")} {DateTime.Now.ToString("yyyy-MM-dd HH: mm:ss.fff")} ***************");
//Action 为框架内置委托
Action<string> action = Calculate;
//回调委托:异步线程结束后执行
AsyncCallback callback = call =>
{
Console.WriteLine($"*************** 异步执行状态: {call.IsCompleted} ***************");
Console.WriteLine($"*************** 自定义对象:{call.AsyncState.ToString()} ***************");
Console.WriteLine($"********************* 回调函数 线程ID:{Thread.CurrentThread.ManagedThreadId.ToString("00")} {DateTime.Now.ToString("yyyy-MM-dd HH: mm:ss.fff")} ***************");
};
//自定义对象
var MyObject = new
{
Description = "今天我们来使用下BeginInovke&EndInvoke实现异步线程",
Date = DateTime.Now,
ByPeople = "WML"
};
IAsyncResult iAsyncResult = action.BeginInvoke("Test", callback, MyObject);
//直接等待异步完成,第一时间进入下一行
//iAsyncResult.AsyncWaitHandle.WaitOne();
//一直等待
//iAsyncResult.AsyncWaitHandle.WaitOne(-1);
//最多等待1000ms
//iAsyncResult.AsyncWaitHandle.WaitOne(1000);
//等待
action.EndInvoke(iAsyncResult);
Console.WriteLine($"********************* 系统结束 线程ID:{Thread.CurrentThread.ManagedThreadId.ToString("00")} {DateTime.Now.ToString("yyyy-MM-dd HH: mm:ss.fff")} ***************");
Console.ReadKey();
}
//异步调用方法
static void Calculate(string name)
{
Console.WriteLine($"*********************异步线程-{name}开始 线程ID:{Thread.CurrentThread.ManagedThreadId.ToString("00")} {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}***************");
long num = 0;
for (int i = 0; i < 10000000; i++)
{
num += i;
}
//等待2s
Thread.Sleep(2000);
Console.WriteLine($"*********************异步线程-{name}结束 线程ID:{Thread.CurrentThread.ManagedThreadId.ToString("00")} {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}***************");
}
}
Action
Action action = () =>
{
Invoke((Action)delegate { biMapNavigation_Click(this.biMapNavigation, new EventArgs()); });
};
action.BeginInvoke(ar =>
{
action.EndInvoke(ar);
if (ar.IsCompleted)
{
PublicDelegate.LocationVehicle?.Invoke(null, new VehicleEventArgs(new Vehicle() { DeviceID = obj, Name = vn }));
}
}, action);
InvokeRequired
//托管调用或者跨线程调用
if (InvokeRequired)
{
Action action = () => pictureBox1.Image = this.imageList1.Images[0];
Invoke(action);
}
匿名委托
ConsumerClient.Instance.Consumer.Connected += delegate
{
Invoke(new MethodInvoker(() =>
{
labNetwork.Text = @"服务已连接";
labNetwork.ForeColor = Color.Green;
}));
};
本文来自博客园,作者:码农阿亮,转载请注明原文链接:https://www.cnblogs.com/wml-it/p/16434294.html
技术的发展日新月异,随着时间推移,无法保证本博客所有内容的正确性。如有误导,请大家见谅,欢迎评论区指正!
开源库地址,欢迎点亮:
GitHub:https://github.com/ITMingliang
Gitee: https://gitee.com/mingliang_it
GitLab: https://gitlab.com/ITMingliang
建群声明: 本着技术在于分享,方便大家交流学习的初心,特此建立【编程内功修炼交流群】,为大家答疑解惑。热烈欢迎各位爱交流学习的程序员进群,也希望进群的大佬能不吝分享自己遇到的技术问题和学习心得!进群方式:扫码关注公众号,后台回复【进群】。