簡體   English   中英

使用 Task.Run 時如何修復“System.Reflection.TargetInvocationException: 'Exception has been throwed by the target of an invocation.'”

[英]How to fix “System.Reflection.TargetInvocationException: 'Exception has been thrown by the target of an invocation.'” when use Task.Run

我是 xamarin.forms 的新手,但是當我嘗試在 xamarin.Forms 中使用 Task.Run 時,出現以下錯誤:

System.Reflection.TargetInvocationException: '調用的目標已拋出異常

到目前為止我的代碼:

 await Task.Run(async () =>
             {
                 await DoWork();
             });

我試過:

 await Task.Run(async () =>
             {
                 await DisplayAlert("hi","hi","hi");
             });

但同樣的錯誤

當你跑

await Task.Run(async() =>
{
    Device.BeginInvokeOnMainThread(async () =>
    {
        // Not blocking main thread since it is still asynchronously called!!!
        await DisplayAlert("hi", $"", "hi");
    });

});

錯誤消息說:

無法在未調用 Looper.prepare() 的線程內創建處理程序

您不能從不是主線程的線程啟動 DisplayAlert! 這就是為什么你必須打電話給

await Task.Run(async() =>
{
    Device.BeginInvokeOnMainThread(async () =>
    {
        await DisplayAlert("hi", $"", "hi");  // Now launched from main thread!!!
    });

});

或者干脆

await DisplayAlert("hi", $"", "hi"); // launched anyway from main thread.

在更一般的情況下,您要避免的是從不是主線程的線程修改 UI,因此如果在“您的”異步方法中您正在修改 UI,則必須通過主線程執行此操作打電話

public async void DoWork()
{
    await DoHeaviWorkAsync();

    Device.BeginInvokeOnMainThread(() =>
    {
        // Make changes to UI
    });
}

在 MainThread 上運行顯示 UI(如DisplayAlert )的代碼:

Device.BeginInvokeOnMainThread(async () =>
{
     await DisplayAlert("hi","hi","hi");
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM