Can I write generic extension method to run task?

前端 未结 1 1500
北恋
北恋 2021-01-29 00:43

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

e.g. a

1条回答
  •  醉梦人生
    2021-01-29 01:17

    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>, which when awaited will return (not await) the actual IAsyncOperation. 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.

    0 讨论(0)
提交回复
热议问题