I am attempting to run async methods from a synchronous method. But I can\'t await the async method since I am in a synchronous method. I must not be und
Task<TResult>.Result (or Task.Wait() when there's no result) is similar to await
, but is a synchronous operation. You should change GetData1()
to use this. Here's the portion to change:
Task<Data> dataTask = Task.WhenAny(runningTasks).Result;
runningTasks.Remove(dataTask);
myData = gameTask.Result;
First, I recommend that your "internal" tasks not use Task.Run
in their implementation. You should use an async
method that does the CPU-bound portion synchronously.
Once your MyAsyncMethod
is an async
method that does some CPU-bound processing, then you can wrap it in a Task
and use parallel processing as such:
internal static void GetData1()
{
// Start the tasks
var dataTasks = Enumerable.Range(0, TotalItems)
.Select(item => Task.Run(() => MyAyncMethod(State[item]))).ToList();
// Wait for them all to complete
Task.WaitAll(dataTasks);
}
Your concurrency limiting in your original code won't work at all, so I removed it for simpilicity. If you want to apply a limit, you can either use SemaphoreSlim
or TPL Dataflow.
You can call the following:
GetData1().Wait();
GetData2().Wait();
GetData3().Wait();