1

Potentially weird request, but I'm attempting to simulate a method call concurrently with the end goal being that i don't care which call to the method reaches it first... the method itself is synchronous (for now) and therefore i know and accept that it will block, i simply don't care which request makes it there first..

this is more of a thought exercise, so if i do something like this, is it doing what i think it's doing? i.e. running the method calls on different threads?

Task<MyObject> t1 = Task.Run(() => MethodToRun("param1"));
Task<MyObject> t2 = Task.Run(() => MethodToRun("param2"));

await Task.WhenAll(t1, t2); // block, and wait for results, i think?

var r1 = t1.Result;
var r2 = t2.Result;

or, will this always end up executing t1 first regardless?

i thought about adding the tasks to a list, and then kicking them all off perhaps..

var taskList = new List<Task<MyObject>>
{
    new Task<MyObject>(() => MethodToRun("param1"));
    new Task<MyObject>(() => MethodToRun("param2"));
};

Parallel.ForEach(taskList, t => t.Start());

await Task.WhenAll(taskList);

var r1 = taskList[0].Result;
var r2 = taskList[1].Result;

is that actually any different?

m1nkeh
  • 1,337
  • 23
  • 45
  • It will usually run them on different threads, yes. Since `Task.Run` uses the thread pool, the two of them _might_ run on the same thread. Also, the second might run before the first. – mjwills Dec 03 '18 at 10:27
  • Why not do `Task.Run(() => MethodToRun("param1"))` inside the List declaration then you wouldn't need the separate invocation to `Start()` them – phuzi Dec 03 '18 at 10:29
  • ok, thanks @mjwills :) so you say this *might* run on diff threads, is there a way i can force it? – m1nkeh Dec 03 '18 at 10:31
  • Possible duplicate of [Task vs Thread differences](https://stackoverflow.com/questions/13429129/task-vs-thread-differences) – mjwills Dec 03 '18 at 10:31
  • 1
    You can 'encourage' it by using `LongRunning` (https://stackoverflow.com/questions/25833054/what-does-long-running-tasks-mean). Or force it by using threads rather than tasks. – mjwills Dec 03 '18 at 10:32
  • haha, @phuzi i had that to start with, but thought it wasn't explicitly doing what i wanted.. thanks for the confirmation - i will simplify that. – m1nkeh Dec 03 '18 at 10:35

0 Answers0