Catch an async lambda exception

瘦欲@ 提交于 2019-12-06 04:42:36

I think that if possible, you should not be doing this. The UI thread should be the one that's managing what happens on the background thread(s), not the other way around.

If you really do need this, you can use the overload of Task.Factory.StartNew() which lets you specify a TaskScheduler, along with Unwrap() to change the resulting Task<Task> into a simple Task:

await Task.Factory.StartNew(
    async () =>
        await CurrentAppSimulator.RequestProductPurchaseAsync("product", true),
    CancellationToken.None, TaskCreationOptions.None, scheduler)
    .Unwrap();

Alternatively, you could use await await:

await await Task.Factory.StartNew(
    async () =>
        await CurrentAppSimulator.RequestProductPurchaseAsync("product", true),
    CancellationToken.None, TaskCreationOptions.None, scheduler);

This means you need to pass the UI TaskScheduler (which you can get by calling TaskScheduler.FromCurrentSynchronizationContext() while you're on the UI thread) to this method.

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