如果我创建一个Func<Task>
并用两种不同的方法填充它们都会执行异步?
public async Task Execute()
{
Func<Task> myFunc = null;
myFunc += async () => {
await WriteCharacters();
};
myFunc += () => {
return WriteCharacters();
};
await myFunc();
}
static async Task WriteCharacters()
{
using (StreamWriter writer = File.CreateText("newfile.txt"))
{
await writer.WriteAsync("Example text as string");
}
}
我对此代码有两个问题。第一个委托是否添加到myFunc,等同于添加的第二个委托?
这些是如何执行的,它们是否会同时执行,还是会在执行第二个之前等待第一个返回?
答案 0 :(得分:1)
是*,以下示例应该有所帮助。
using System;
using System.IO;
using System.Threading.Tasks;
namespace Test
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Before Execute ");
Execute();
Console.WriteLine("After Execute ");
Console.ReadLine();
}
static async Task Execute()
{
Func<Task> myFunc = null;
myFunc += async () => {
Console.WriteLine("in async func");
await WriteCharacters();
};
myFunc += () => {
Console.WriteLine("in func");
return WriteCharacters();
};
await myFunc();
}
static async Task WriteCharacters()
{
await Task.Delay(4000);
using (StreamWriter writer = File.CreateText("newfile.txt"))
{
Console.WriteLine("Writeing the file");
await writer.WriteAsync("Example text as string");
}
}
}
}
*当第一个方法到达await语句
时,第二个将开始