Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
665 views
in Technique[技术] by (71.8m points)

c# - What is a correct way to await for dictionary with async action?

Usually when I have await in a scope of a method I need to mark method as async and return Task<>. In a code below compiler allowed me to resolve an async/await action inside a dictionary, I was wondering if it is safe to return void from a method in such case. Please consider a following code:

public void Consume(int ServiceId, MyContext ctx){
  var consumerProvider = new Dictionary<int, Action<SomeClass>>{
    {1, 
       async (consumerContext) => await FirstService.ConsumeAsync(consumerContext)},
    {2, 
       async (consumerContext) => await SecondService.ConsumeAsync(consumerContext)},
  };

  consumerProvider[serviceId](ctx);
}

Again, I am just interested to learn if such wrapped async/await in the dictionary is safe or Consume method should return something else than void, and be marked as async.

I am not interested in refactoring this code not to face this challenge or to improve code quality. I am seeking to deeper understand async/await that is wrapped in some data structure, such as Dictionary.

question from:https://stackoverflow.com/questions/65887083/what-is-a-correct-way-to-await-for-dictionary-with-async-action

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Is this code problematic?

- Yes. Because you are basically having an async void method. Which is bad: See Avoid async void

Putting it into a Dictionary or any other datastructure will not improve on this.

Why don't I see people recommend against it more frequently?

In comments, we talked about Parallel.ForEach and that there are a lot of recommendations or warnings to not mix it with async/await.

That's because there, the problem is the combination of the two. Parallel is perfectly fine. Async/await is perfectly fine. But if you mix them, they turn explosive.

async void on the other hand is problematic in and by itself. So you'll probably read a lot of "dude, that method is async void, dont' do that", so that's what you'll be warned about. Not so much the combination with a Dictionary, which in itself is no problem. You could have a Dictionary<int, Func<TContext,Task>> perfectly fine.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...