异步回调:主线程在执行的时候,打开一个子线程,主线程继续执行,当子线程执行完成的时候,主线程立即输出主线程的运行结果,主线程继续执行。

注意:

1.调用BeginInvoke开始异步加载, 在 ThreadPool 线程上执行回调方法,而不是在主线程。

2.调用 EndInvoke 来完成异步调用。

3.定义的委托,可以没有参数,没有返回值,看具体功能需求。

using System;
using System.Threading;

namespace StructScript
{
public class AsyncMain
{
public delegate string AsyncDelegate();

private static void Main(string[] args)
{
AsyncDelegate dlgt = new AsyncDelegate(LoadAsync);
//异步加载开始
IAsyncResult ar = dlgt.BeginInvoke(LoadFinished, dlgt);
Console.WriteLine("Loading...");
Console.ReadLine();
}

//异步加载进行中
private static string LoadAsync()
{
Console.WriteLine("LoadAsync begins.");
int sleepTime = 3000;
Thread.Sleep(sleepTime);
return "My runtime was " + sleepTime.ToString();
}

//异步加载完成
private static void LoadFinished(IAsyncResult ar)
{
if(ar == null)
{
Console.WriteLine("IAsyncResult is null");
}
AsyncDelegate dlgt = ar.AsyncState as AsyncDelegate;
string ret = dlgt.EndInvoke(ar);
Console.WriteLine("LoadFinished with return value \"{0}\".", ret);
}
}
}

输出结果:

 

C#--异步回调_异步加载