Webezine
Webezine

Reputation: 456

Chain two methods into tasks

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() ));

Upvotes: 1

Views: 298

Answers (3)

Andrew Jones
Andrew Jones

Reputation: 41

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.

Upvotes: 0

miechooy
miechooy

Reputation: 3422

If methods are async you can do:

await MethodX();
await MethodY();

@Edit when void

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

Upvotes: 0

Camilo Terevinto
Camilo Terevinto

Reputation: 32072

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();
}

Upvotes: 4

Related Questions