/// 耗时方法
/// </summary>
/// <param name="name"></param>
private void DoSomeThing(string name)
{
Console.WriteLine($"开始执行{name}, {Thread.CurrentThread.ManagedThreadId.ToString("00")} ,{DateTime.Now}");
int num = 1;
for (int i = 0; i < 100000000; i++)
{
num++;
}
Thread.Sleep(1000);
Console.WriteLine($"结束执行{name}, {Thread.CurrentThread.ManagedThreadId.ToString("00")} ,{DateTime.Now},{num}");
}
/// 同步方法 按钮
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
Action<string> act = this.DoSomeThing;
for (int i = 0; i < 5; i++)
{
act.Invoke("button1_Click");
}
Console.WriteLine("计算之后干什么");
}
/// 异步方法
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
Action<string> act = this.DoSomeThing;
AsyncCallback asyncCallback = ar => Console.WriteLine("回调函数"); //回调函数
IAsyncResult result = null;
for (int i = 0; i < 5; i++)
{
result = act.BeginInvoke("button2_Click", asyncCallback, "小猪");
}
act.EndInvoke(result);
IAsyncResult iAsyncResult = atc.BeginInvoke("上传文件", ar => Console.WriteLine("执行回调函数"), null);
int i = 1;
while (!iAsyncResult.IsCompleted)
{
if (i < 10)
{
Console.WriteLine($"文件上传{i++ * 10}");
}
else
{
Console.WriteLine($"已完成99%....马上结束");
}
Thread.Sleep(100);
}
Console.WriteLine("上传完成");