简体   繁体   English

将两种方法链接到任务中

[英]Chain two methods into tasks

I'm teaching myself c# and struggling to understand threading, async and the like. 我正在自学c#,并努力理解线程,异步等。 I'm trying to do some practical exercises to improve my knowledge. 我正在尝试做一些实践练习来提高我的知识。

I have two methods : method x and method Y 我有两种方法:方法x和方法Y

I need to create a task which will run method X and once method x is finished it will run method y. 我需要创建一个将运行方法X的任务,一旦方法x完成,它将运行方法y。

I then want to build on this and create the same task three times. 然后,我想以此为基础并创建三次相同的任务。 so essentially three different task which run the two methods. 因此本质上是运行这两种方法的三个不同的任务。

The methods are public void . 这些方法是public void I tried something like this: 我尝试过这样的事情:

Task[] tasks = new Task[2];
tasks[1] = Task.Run(() => x(n1.ToString()));
tasks[2] = tasks[1].ContinueWith(antecedent => y() ));

If MethodX and MethodY are: 如果MethodXMethodY为:

public async Task MethodX() {}
public async Task MethodY() {}

then, you can use: 然后,您可以使用:

await MethodX();
await MethodY();

If MethodX and MethodY are: 如果MethodXMethodY为:

public void MethodX() {}
public void MethodY() {}

then, you can use: 然后,您可以使用:

await Task.Run(() => 
{ 
    MethodX();
    MethodY();
}

If methods are async you can do: 如果方法异步,则可以执行以下操作:

await MethodX();
await MethodY();

@Edit when void @无效时编辑

  await Task.Run(() => MethodX());
  await Task.Run(() => MethodY());

you can create a list of Task then define your task as you build up your collection: 您可以创建任务列表,然后在建立集合时定义任务:

List<Task> TasksToDo = new List<Task>();

TasksToDo.AddRange(from item in someCollection.AsEnumerable()
                   select new Task(() => {
                                            MethodX();
                                            MethodY();
                                         }));

TasksToDo.ForEach(x => x.Start());
Task.WaitAll(TasksToDo.ToArray());

You've not specified you need it but if needs be you can specify Task<t> and declare a return type to get from TasksToDo once all complete. 您尚未指定是否需要它,但是如果需要,可以指定Task<t>并声明一个返回类型,以在完成所有操作后从TasksToDo获取。

Hope that helps. 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM