0

I'm programming an iOS/Android app in Xamarin. At some points, I want to call asynchronous methods in the shared layer. Sometimes I call a method without awaiting it so other methods can be called. For example when values in the database should be updated (the shared layer handles read/write collisions). I do not care when the method call is finished and therefore I declare the method async void. Visual Studio now shows a warning "asynchronous method '...' should not return void". I know exactly that the method should not be awaited, so why shouldn't the method return void at that point? If I change the return type to task instead, I get warnings to consider using await for the method call which I don't want to.

Another example is retrieving data from the database and updating the UI when the data becomes available. This time I await the method call to the shared layer but in an async void method in the UI class. I want the execution to continue while the data is retrieved, so why is it bad to have an async void method?

klashar
  • 2,519
  • 2
  • 28
  • 38
Superwayne
  • 1,146
  • 1
  • 12
  • 22
  • 2
    Are you sure you don't want to `await` your reads and writes? This means that you can't catch exceptions. – Stephen Cleary Feb 17 '17 at 20:47
  • Async void is bad because you cannot await it (and so cannot handle exceptions from it). If you create such method - ensure method itself handles all possible exceptions (top level try catch block with meaningful handling). Not awaiting async method is sometimes appropriate (especially if you do something with returned Task later). – Evk Feb 17 '17 at 20:57
  • 1
    Possible duplicate of [Is it OK to declare an async method as returning void to silence the CS4014 warning?](http://stackoverflow.com/questions/32766032/is-it-ok-to-declare-an-async-method-as-returning-void-to-silence-the-cs4014-warn) – klashar Feb 17 '17 at 21:12
  • For you UI example, look in to [NotifyTaskCompleteion](https://github.com/StephenCleary/AsyncEx/wiki/NotifyTaskCompletion) (written by the guy who wrote the first comment in this post too!) You have the notify class hold the running task and you can bind to the notify object and it has useful properties like IsRunning and whatnot. – Scott Chamberlain Feb 17 '17 at 23:07
  • Exceptions are completely handled in the search layer. And at some points I have to make a method async void. For example when I overwrite "ViewDidLoad", I can only use async void if I want to await a Task. – Superwayne Feb 18 '17 at 14:21
  • @ScottChamberlain I'll have a look at it but I don't really understand how to use it. What's the difference to just awaiting the Task (which I have to do before I can update the UI)? – Superwayne Feb 18 '17 at 14:24

0 Answers0