简体   繁体   中英

Cannot implicitly convert type 'void' to 'object' on GetAwaiter().GetResult()

We have used the following code to await method execution since we have sync methods that must consume async methods and this is a wrapper we have used in our project

public dynamic RunTask(dynamic method) {
   var result = Task.Run(async () => await method).ConfigureAwait(false);
   return result.GetAwaiter().GetResult();
}

Seems like this line of code works fine when the method have return types ex: Task< int > but today when I have written non-return method it throws an exception when there is no return value from Task

   // throws exception in this case 'Cannot implicitly convert type 'void' to 'object'
   public async Task Run(){
        await //;
   }

   // Works
   public async Task<int> Fun(){
      return await //;
   }

From the message, it is clearly unable to assign void to object but is there something I am missing how do I make it work void tasks. We are using .net core 3.1. Any help is greatly appreciated.

Are you calling RunTask(); with the method not returning anything? :)

First of this a bad practice. The best way to async call is following await pattern. This goes something like this

private Task MyMethodAsync(){

}


public async void Main(){
    await MyMethodAsync();
}

Now it can be a bit difficult to implement await pattern if it's not already in place (as it may require await-ing all the calls in chain). What you can you do is the following:

MyMethodAsync().Wait()

This will block the calling thread and wait till the task is done. Since it's void you won't get any result and that's the main reason you are getting this exception in the first place.

You can try this code for your purpose, however as Marc suggested, this is not recommended practice:

   public dynamic RunTask(dynamic method)
    {
       if (method is Task)
        {
            method.ConfigureAwait(false).GetAwaiter().GetResult();
            return 0;
        }
        else
        {
            var result = Task.Run(async () => await method).ConfigureAwait(false);
            return result.GetAwaiter().GetResult();
        }

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM