Home > OS >  Should you wrap an asynchronous operation which you don't need to await in a Task.Run()?
Should you wrap an asynchronous operation which you don't need to await in a Task.Run()?

Time:06-07

My WPF application is sometimes running code in the background which does not need to be awaited, should I wrap it into Task.Run() or leave the method call alone with the warning "Because this call is not awaited..."?

CodePudding user response:

You should wrap it in Task.Run(() => ... );.

You should also not add async to the signature if you are not awaiting anything.

CodePudding user response:

Tasks are assigned to threads by the scheduler, and scheduler takes current pressure, number of cores, pending tasks and a few other aspects in determining how many (and if any) threads should be started.

In that light, wrapping code into Task.Run() does not necessarily add any pressure to the system, other than one indirection to the scheduler which would dispatch work to an existing thread.

On the other hand, unless you are publishing code and must refraom from breaking changes, it will probably be easier for you to not return a Task now, but wait until a later change forces you to go asynchronous. That may happen in case that your method is effectively implementing an interface member, and that interface attains a truly asynchronous implementation later. When that happens, you would have to fix the existing method, and to change all the callers - which may cause trouble, depending on the project.

I myself usually start simple - non-asynchronous method first - and then let it evolve into an async one when needed.

Please bear in mind that async is effectively breaking principles of good OOD, because asynchronous design is mixed together with functional design. It doesn't make much sense to force adding async to methods that are not truly asynchronous, if for no other reason then because once in a while you might really really really need that method to run on the current thread - and what would you do then? Break the design once more.

  • Related