1

I'm teaching myself c# and struggling to understand threading, async and the like. I'm trying to do some practical exercises to improve my knowledge.

I have two methods : method x and method Y

I need to create a task which will run method X and once method x is finished it will run method 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. I tried something like this:

Task[] tasks = new Task[2];
tasks[1] = Task.Run(() => x(n1.ToString()));
tasks[2] = tasks[1].ContinueWith(antecedent => y() ));
Theraot
  • 31,890
  • 5
  • 57
  • 86
Webezine
  • 345
  • 7
  • 22
  • If they have to execute sequentially, why Task up X and Y at all? – Lloyd Nov 23 '17 at 13:22
  • For what I an tell, you can just call them sequentially. If you want a different behavior, it is not clear. – Theraot Nov 23 '17 at 13:24
  • Three different tasks, that run sequentially or in parallel? – Lloyd Nov 23 '17 at 13:34
  • Isn't their an issue here that your methods if they are public void Foo(), are going ot run synchronously anyway. Don't you want them to be public Task Foo(). (Task being the async equivalent to void) – Stuart Nov 23 '17 at 13:40

3 Answers3

4

If MethodX and MethodY are:

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

then, you can use:

await MethodX();
await MethodY();

If MethodX and MethodY are:

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

then, you can use:

await Task.Run(() => 
{ 
    MethodX();
    MethodY();
}
Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
0

If methods are async you can do:

await MethodX();
await MethodY();

@Edit when void

  await Task.Run(() => MethodX());
  await Task.Run(() => MethodY());
miechooy
  • 3,178
  • 12
  • 34
  • 59
  • they are public voids. I tried something like: Task[] tasks = new Task[2]; tasks[1] = Task.Run(() => x(n1.ToString())); tasks[2] = tasks[1].ContinueWith(antecedent => y() )); – Webezine Nov 23 '17 at 13:22
0

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.

Hope that helps.