Calling an async method from a synchronous method

前端 未结 3 975
忘掉有多难
忘掉有多难 2020-12-09 18:47

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

相关标签:
3条回答
  • 2020-12-09 19:06

    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;
    
    0 讨论(0)
  • 2020-12-09 19:10

    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.

    0 讨论(0)
  • You can call the following:

    GetData1().Wait();
    GetData2().Wait();
    GetData3().Wait();
    
    0 讨论(0)
提交回复
热议问题