Norgul Norgul - 1 month ago 21
C# Question

C# wait DLL async method to finish

I have a DLL which has

public Task<>
method which returns
return Task.Factory.StartNew(() => ...)
. I am calling it within a program and I want the program to wait for the execution of the task to finish before it continues doing other things. I've added
Thread.Sleep(6000)
to the DLL to simulate longer execution.

When I'm calling it like this

var invokedTask = myMethod.Invoke(Activator.CreateInstance(myClass), myParams);


It just continues with execution (as expected). But then I tried this:

var invokedTask = Task.Factory.StartNew(() => myMethod.Invoke(Activator.CreateInstance(myClass), myParams));
invokedTask.Wait();


And it doesn't work. How can I make it wait from outside of DLL?

Answer

Just Wait for the task that is being returned - don't spin up another Task just to call the original method:

var invokedTask = (Task)myMethod.Invoke(Activator.CreateInstance(myClass), myParams);
invokedTask.Wait();