async与await线程分配研究

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks; namespace ATLearn
{
/// <summary>
/// Guid工厂
/// </summary>
static class GuidFactory
{
//private static ThreadLocal<string> _localGuid = new ThreadLocal<string>();
private static AsyncLocal<string> _localGuid = new AsyncLocal<string>();
public static string CurrentGuid
{
get
{
if (_localGuid.Value == null)
{
_localGuid.Value = Guid.NewGuid().ToString();
}
return _localGuid.Value;
}
}
} class APP
{
private Task<int> awaitFunction(int taskId)
{
return Task.Factory.StartNew((obj) =>
{
int itaskId = (int)obj;
Console.WriteLine(string.Format("taskId: {0} Await! threadId: {1} Guid: {2}", taskId, Thread.CurrentThread.ManagedThreadId, GuidFactory.CurrentGuid));
Thread.Sleep();
return itaskId;
}, (object)taskId);
} private async void asyncFunction(int taskId)
{
Console.WriteLine(string.Format("taskId: {0} Start! threadId: {1} Guid: {2}", taskId, Thread.CurrentThread.ManagedThreadId, GuidFactory.CurrentGuid));
int num = await awaitFunction(taskId);
Console.WriteLine(string.Format("taskId:{0} End! threadId: {1} Guid: {2}", taskId, Thread.CurrentThread.ManagedThreadId, GuidFactory.CurrentGuid));
} public APP()
{
for (int i = ; i <= ; ++i)
{
asyncFunction(i);
} while (true)
{
Thread.Sleep();
}
}
} class Program
{
static void Main(string[] args)
{
APP App = new APP();
}
}
}

async与await线程分配研究

可见await会开新线程

async标志的函数为异步函数,异步函数内部,在进行await的时候会等待await后面一个线程运行结束

而第一次await的时候,异步函数就会跳过,执行主线程里异步函数之后的内容了

上一篇:Android 4.4以上的存储读写权限


下一篇:关于 android 中 postDelayed方法的讲解