我试图从异步方法执行两个不同的任务,但我的第二个任务只应该从第一个结束的地方开始。我尝试使用 ContinueWith 但没有成功。这是我的示例代码:
class Program
{
static List<string> GlobalList1 = null;
static List<string> GlobalList2 = null;
static void Main(string[] args)
{
Task firstTask = new Task(DoFirstThing);
firstTask.Start();
firstTask.Wait();
Task secondTask = firstTask.ContinueWith(o => DoSecondThing(), TaskContinuationOptions.ExecuteSynchronously);
secondTask.Wait();
Console.ReadKey();
}
public async static void DoFirstThing()
{
Console.WriteLine("Doing first...");
Task t = new Task(FirstThing);
t.Start();
await t;
}
public async static void DoSecondThing()
{
Console.WriteLine("Doing second...");
Task t = new Task(SecondThing);
t.Start();
await t;
}
private async static void FirstThing()
{
Console.WriteLine("In First..");
Task t = new Task(() =>
{
List<string> list = new List<string>();
for (int i = 0; i < 1000; i++)
{
list.Add(string.Format("Testing:{0}", i));
}
System.Threading.Thread.Sleep(2000);
GlobalList1 = list;
});
t.Start();
await t;
}
private async static void SecondThing()
{
Console.WriteLine("In Second...");
Task t = new Task(() =>
{
GlobalList2 = new List<string>();
for (int i = 0; i < GlobalList1.Count; i++)
{
GlobalList2.Add(GlobalList1[i].ToString() + " - testing");
}
});
t.Start();
await t;
}
}
您可能会通过控制台输出注意到任务保持同时运行。是否有可能改变这种行为?