Can I write generic extension method to run task?

若如初见. 提交于 2019-12-02 17:53:18

问题


I am calling this method: Windows.Foundation.IAsyncOperation<AppServiceResponse> AppServiceConnection.SendMessageAsync(ValueSet message)

e.g. await connection.SendMessageAsync(initialStatus);

It shows an error: 'IAsyncOperation' does not contain a definition for "GetAwaiter" and no extension method "GetAwaiter" accepting a first argument of type 'IAsyncOperation'could be found (are you missing a using directive for 'System'?)

Then I change it to:

await Task.Run(() => connection.SendMessageAsync(initialStatus));

It got compiled.

My first question is why I cannot apply await to SendMessageAsync? What exactly does it mean "no definition for GetAwaiter"?

My second question is I also need to run other methods e.g. Windows.Foundation.IAsyncOperation<AppServiceConnectionStatus> AppServiceConnection.OpenAsync()

I write an extension method:

public static async void AsTask(this IAsyncOperation<AppServiceResponse> operation)
{
    await Task.Run(() => operation);
}

So I can call connection.SendMessageAsync(initialStatus).AsTask(); But can I make the extension method generic so I can also call something like connection.OpenAsync().AsTask();


回答1:


My first question is why I cannot apply await to SendMessageAsync? What exactly does it mean "no definition for GetAwaiter"?

It means you're missing a reference to System.Runtime.WindowsRuntime.dll.

Then I change it to [use Task.Run] It got compiled.

Yes, but it won't work right. As mike commented, the return type of Task.Run here is Task<IAsyncOperation<T>>, which when awaited will return (not await) the actual IAsyncOperation<T>. So you're just starting the operation on a background thread and then awaiting for that operation to start - you're not awaiting for it to complete.

So, you shouldn't write an extension method. You shouldn't be using Task.Run at all here. Just add the missing reference, and you should be fine.



来源:https://stackoverflow.com/questions/42450602/can-i-write-generic-extension-method-to-run-task

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!