一、实例1
static void Main(string [] args)
{
Console.WriteLine("开始线程");
startFunc();
Console.WriteLine("结束线程");
Console.ReadKey();
}
public static Task GetValue()
{
return Task.Run(() => {
for (int i = 0; i < 1000; i++)
{
Console.WriteLine("第{“"+i+"”位数!}");
}
});
}
/// <summary>
/// 该方法是线程执行完后再继续执行里面其他方法
/// </summary>
public static async void startFunc()
{
await GetValue();
Console.WriteLine("线程结束");
}
截图1:
截图2:
二、实例2
public delegate void PrintDelegate(string s);
static void Main(string[] args)
{
PrintDelegate printDelegate = Print;
Console.WriteLine("开始主线程");
IAsyncResult result = printDelegate.BeginInvoke("Hello World.", null, null);
Console.WriteLine("主线程继续执行...");
//当使用BeginInvoke异步调用方法时,如果方法未执行完,EndInvoke方法就会一直阻塞,直到被调用的方法执行完毕
printDelegate.EndInvoke(result);
Console.WriteLine("当异步线程执行完后执行...");
Console.ReadKey(true);
}
public static void Print(string s)
{
Console.WriteLine("异步线程开始执行:" + s);
for (int i = 0; i < 1000; i++)
{
Console.WriteLine("第{"+i+"}位数");
}
}
图1:
图2:
二、实例3
首先写一个静态的线程类:TaskAsyncHelper
public static class TaskAsyncHelper
{
/// <summary>
/// 将一个方法function异步运行,在执行完毕时执行回调callback
/// </summary>
/// <param name="function">异步方法,该方法没有参数,返回类型必须是void</param>
/// <param name="callback">异步方法执行完毕时执行的回调方法,该方法没有参数,返回类型必须是void</param>
public static async void RunAsync(Action function, Action callback)
{
Func<System.Threading.Tasks.Task> taskFunc = () =>
{
return System.Threading.Tasks.Task.Run(() =>
{
function();
});
};
await taskFunc();
if (callback != null)
callback();
}
/// <summary>
/// 将一个方法function异步运行,在执行完毕时执行回调callback
/// </summary>
/// <typeparam name="TResult">异步方法的返回类型</typeparam>
/// <param name="function">异步方法,该方法没有参数,返回类型必须是TResult</param>
/// <param name="callback">异步方法执行完毕时执行的回调方法,该方法参数为TResult,返回类型必须是void</param>
public static async void RunAsync<TResult>(Func<TResult> function, Action<TResult> callback)
{
Func<System.Threading.Tasks.Task<TResult>> taskFunc = () =>
{
return System.Threading.Tasks.Task.Run(() =>
{
return function();
});
};
TResult rlt = await taskFunc();
if (callback != null)
callback(rlt);
}
}
然后调用该方法
static void Main(string[] args)
{
Console.WriteLine("开始调用");
sa();
TaskAsyncHelper.RunAsync(a, b);
Console.WriteLine("end");
Console.ReadKey();
}
public static async void sa()
{
string b = await getValue("朱哥");
Console.WriteLine(b);
}
public static Task<string> getValue(string name)
{
return Task.Run(() =>
{
return "欢迎你" + name;
});
}
public static void a()
{
Console.WriteLine("a()");
}
public static void b()
{
Console.WriteLine("b()");
}
效果图: