I'm trying to learn how to use async tasks and am really struggling just to get a simple example working. I provide a very simplified version of what I'm trying to achieve below.
public void Calculate()
{
int a1 = 1;
int a2 = 2;
int b1 = 3;
int b2 = 4;
int c3 = 5;
int c4 = 6;
int c5 = 7;
int c6 = 8;
int c7 = 9;
// Do next 2 lines in parallel
int rank1 = Evaluate(a1, a2, c3, c4, c5, c6, c7);
int rank2 = Evaluate(b1, b2, c3, c4, c5, c6, c7);
// wait for above 2 lines and use values to get result
int result = EvaluateOutcome(rank1, rank2);
}
public static int Evaluate(int i1, int i2, int i3, int i4, int i5, int i6, int i7)
{
// do something complicated and return value - simulate here with random number
Random rand = new Random();
return rand.Next(0,10);
}
public static int EvaluateOutcome(int rank1, int rank2)
{
return rank1 * rank2;
}
Calculating rank1
and rank2
is a long process in my real code but the calculations are independent of each other. I'd like to try to run both calculations at once to hopefully half the processing time. I need to await both calculations completing prior to calculating result.
I think I should be able to do something like:
private async Task Evaluate(int a1, int a2, int b1, int b2, int c3, int c4, int c5, int c6, int c7)
{
Task task1 = Evaluate(a1, a2, c3, c4, c5, c6, c7);
Task task2 = Evaluate(b1, b2, c3, c4, c5, c6, c7);
await Task.WhenAll(task1, task2);
}
But this does not compile and I'm unsure how to get the results from the Task and put them into my rank1
and rank2
int variables. I think this should be incredibly simple but I can't find a clear example to follow. Some help would be appreciated.