System.AggregateException: 发生了一个或多个错误。 (任务已取消。)

huangapple go评论89阅读模式
英文:

System.AggregateException: One or more errors ocurred. (A task was canceled.)

问题

我正在尝试调用LoadPickerData方法,以使用async/await从ViewModel加载Picker中的结果。我收到以下错误:

错误

System.AggregateException
Message=发生了一个或多个错误。(任务已取消。)
Source=mscorlib
StackTrace:
在 System.Threading.Tasks.Task.ThrowIfExceptional(System.Boolean includeTaskCanceledExceptions) [0x00011] in /Users/builder/jenkins/workspace/archive-mono/2019-08/android/release/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs:2027
在 System.Threading.Tasks.Task1[TResult].GetResultCore(System.Boolean waitCompletionNotification) [0x0002b] in /Users/builder/jenkins/workspace/archive-mono/2019-08/android/release/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/Future.cs:496 在 System.Threading.Tasks.Task1[TResult].get_Result() [0x00000] in /Users/builder/jenkins/workspace/archive-mono/2019-08/android/release/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/Future.cs:466
在 EmployeeApp.Helpers.ConnectivityHelper.CheckConnectivity() [0x00049] in F:\Workspace\BajaDev\MPA_Project\EmployeeApp\Helpers\ConnectivityHelper.cs:34
在 EmployeeApp.Helpers.ConnectivityHelper.get_IsConnected() [0x00000] in F:\Workspace\BajaDev\MPA_Project\EmployeeApp\Helpers\ConnectivityHelper.cs:21
在 EmployeeApp.ViewModels.BaseViewModel.get_ServiceAreaStore() [0x00000] in F:\Workspace\BajaDev\MPA_Project\EmployeeApp\ViewModels\BaseViewModel.cs:27
在 EmployeeApp.ViewModels.MailboxViewModel.GetPickerServiceArea() [0x0000f] in F:\Workspace\BajaDev\MPA_Project\EmployeeApp\ViewModels\MailboxViewModel.cs:60
在 EmployeeApp.MailboxPage.LoadPickerData() [0x0002b] in F:\Workspace\BajaDev\MPA_Project\EmployeeApp\Views\MailBoxPage.xaml.cs:70
在 EmployeeApp.MailboxPage.OnAppearing() [0x0002c] in F:\Workspace\BajaDev\MPA_Project\EmployeeApp\Views\MailBoxPage.xaml.cs:31
在 System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.<ThrowAsync>b__7_0(System.Object state) [0x00000] in /Users/builder/jenkins/workspace/archive-mono/2019-08/android/release/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/AsyncMethodBuilder.cs:1021
在 Android.App.SyncContext+<>c__DisplayClass2_0.<Post>b__0() [0x00000] in <06692e0cad5848598a0f46942a89e99f>:0
在 Java.Lang.Thread+RunnableImplementor.Run() [0x00008] in <06692e0cad5848598a0f46942a89e99f>:0
在 Java.Lang.IRunnableInvoker.n_Run(System.IntPtr jnienv, System.IntPtr native__this) [0x00009] in <06692e0cad5848598a0f46942a89e99f>:0
在 (wrapper dynamic-method) Android.Runtime.DynamicMethodNameCounter.44(intptr,intptr)

我试图在Picker中加载GET请求的结果,但当我首次启动应用程序时,它不起作用,我收到了上述异常,第二次运行它时不再出现该错误。
我查找了原因,发现我在构造函数中调用了一个异步方法,这是不好的代码,我将它更改为OnAppearing()方法,但仍然出现该异常,我还不知道原因是什么。

MailboxPage.xaml.cs

public MailboxPage()
{
    InitializeComponent();
    BindingContext = viewModel = new MailboxViewModel();
}

protected override async void OnAppearing()
{
    base.OnAppearing();
    await LoadPickerData();
}

private async Task<IEnumerable<ServiceArea>> LoadPickerData()
{
    var vm = new MailboxViewModel();
    var servicesareas = await vm.GetPickerServiceArea();
    try
    {
        ServiceAreaPicker.ItemsSource = servicesareas.ToList();
        ServiceAreaPicker.ItemDisplayBinding = new Binding("Name");
    }
    catch (AggregateException ae)
    {
        foreach (var e in ae.Flatten().InnerExceptions)
        {
            Debug.WriteLine($"{e.GetType().FullName} { e.Message}");
        }
    }
    return servicesareas;
}

MailboxViewModel.cs

public async Task<IEnumerable<ServiceArea>> GetPickerServiceArea()
{
    try
    {
        PickerItems = await ServiceAreaStore.GetPickerItemsAsync(true);
        foreach (var item in PickerItems)
            Items.Add(item);
    }
    catch (AggregateException ae)
    {
        foreach (var e in ae.Flatten().InnerExceptions)
        {
            Debug.WriteLine($"{e.GetType().FullName} { e.Message}");
        }
    }
    return PickerItems;
}

ServiceAreaStoreAPI.cs

public async Task<IEnumerable<ServiceArea>> GetPickerItemsAsync(bool forceRefresh = false)
{
    if (forceRefresh)
    {
        var json = await Client.GetStringAsync("api/servicearea");
        Servicesareas = await Task.Run(() => JsonConvert.DeserializeObject<IEnumerable<ServiceArea>>(json));
        try
        {
            var success = LocalDatabase.AddItemsAsync(Servicesareas);
            if (!success.Result)
            {
                // Log de fallo en la insercion de datos.
            }
        }
        catch (AggregateException ae)
        {
            foreach (var e in ae.Flatten().InnerExceptions)
            {
                Debug.WriteLine($"{e.GetType().FullName} { e.Message}");
            }
        }
    }
    return Servicesareas;
}
英文:

I'm trying to call LoadPickerData method to load the result in a Picker using async/await from the a ViewModel. I get the following error:
System.AggregateException: 发生了一个或多个错误。 (任务已取消。)

Error

System.AggregateException
  Message=One or more errors occurred. (A task was canceled.)
  Source=mscorlib
  StackTrace:
  at System.Threading.Tasks.Task.ThrowIfExceptional (System.Boolean includeTaskCanceledExceptions) [0x00011] in /Users/builder/jenkins/workspace/archive-mono/2019-08/android/release/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs:2027 
  at System.Threading.Tasks.Task`1[TResult].GetResultCore (System.Boolean waitCompletionNotification) [0x0002b] in /Users/builder/jenkins/workspace/archive-mono/2019-08/android/release/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/Future.cs:496 
  at System.Threading.Tasks.Task`1[TResult].get_Result () [0x00000] in /Users/builder/jenkins/workspace/archive-mono/2019-08/android/release/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/Future.cs:466 
  at EmployeeApp.Helpers.ConnectivityHelper.CheckConnectivity () [0x00049] in F:\Workspace\BajaDev\MPA\_Project\EmployeeApp\Helpers\ConnectivityHelper.cs:34 
  at EmployeeApp.Helpers.ConnectivityHelper.get_IsConnected () [0x00000] in F:\Workspace\BajaDev\MPA\_Project\EmployeeApp\Helpers\ConnectivityHelper.cs:21 
  at EmployeeApp.ViewModels.BaseViewModel.get_ServiceAreaStore () [0x00000] in F:\Workspace\BajaDev\MPA\_Project\EmployeeApp\ViewModels\BaseViewModel.cs:27 
  at EmployeeApp.ViewModels.MailboxViewModel.GetPickerServiceArea () [0x0000f] in F:\Workspace\BajaDev\MPA\_Project\EmployeeApp\ViewModels\MailboxViewModel.cs:60 
  at EmployeeApp.MailboxPage.LoadPickerData () [0x0002b] in F:\Workspace\BajaDev\MPA\_Project\EmployeeApp\Views\MailBoxPage.xaml.cs:70 
  at EmployeeApp.MailboxPage.OnAppearing () [0x0002c] in F:\Workspace\BajaDev\MPA\_Project\EmployeeApp\Views\MailBoxPage.xaml.cs:31 
  at System.Runtime.CompilerServices.AsyncMethodBuilderCore+&lt;&gt;c.&lt;ThrowAsync&gt;b__7_0 (System.Object state) [0x00000] in /Users/builder/jenkins/workspace/archive-mono/2019-08/android/release/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/AsyncMethodBuilder.cs:1021 
  at Android.App.SyncContext+&lt;&gt;c__DisplayClass2_0.&lt;Post&gt;b__0 () [0x00000] in &lt;06692e0cad5848598a0f46942a89e99f&gt;:0 
  at Java.Lang.Thread+RunnableImplementor.Run () [0x00008] in &lt;06692e0cad5848598a0f46942a89e99f&gt;:0 
  at Java.Lang.IRunnableInvoker.n_Run (System.IntPtr jnienv, System.IntPtr native__this) [0x00009] in &lt;06692e0cad5848598a0f46942a89e99f&gt;:0 
  at (wrapper dynamic-method) Android.Runtime.DynamicMethodNameCounter.44(intptr,intptr)

I'm trying to load the result of a GET request in a picker, but when I start the app the first time, it does not and I get the previous exception and the second time I run it I no longer get that error.
I looked for why and I was making the call of an asynchronous method in a constructor and that is bad code, I changed it to an OnAppearing () method but still that exception keeps coming out and I don't have idea the why yet

MailboxPage.xaml.cs

public MailboxPage()
    {
        InitializeComponent();

        BindingContext = viewModel = new MailboxViewModel();
    }

    protected override async void OnAppearing()
    {
        base.OnAppearing();
        await LoadPickerData();
    }

private async Task&lt;IEnumerable&lt;ServiceArea&gt;&gt; LoadPickerData()
    {
        var vm = new MailboxViewModel();

        var servicesareas = await vm.GetPickerServiceArea();
        try
        {
            ServiceAreaPicker.ItemsSource = servicesareas.ToList();
            ServiceAreaPicker.ItemDisplayBinding = new Binding(&quot;Name&quot;);
        }
        catch(AggregateException ae)
        {
            foreach (var e in ae.Flatten().InnerExceptions)
            {
                Debug.WriteLine($&quot;{e.GetType().FullName} { e.Message}&quot;);
            }
        }

        return servicesareas;
    }

MailboxViewModel.cs

public async Task&lt;IEnumerable&lt;ServiceArea&gt;&gt; GetPickerServiceArea()
    {
        try
        {
            PickerItems = await ServiceAreaStore.GetPickerItemsAsync(true);
            foreach (var item in PickerItems)
                Items.Add(item);
        }
        catch (AggregateException ae)
        {
            foreach (var e in ae.Flatten().InnerExceptions)
            {
                Debug.WriteLine($&quot;{e.GetType().FullName} { e.Message}&quot;);
            }
        }

        return PickerItems;
    }

ServiceAreaStoreAPI.cs

public async Task&lt;IEnumerable&lt;ServiceArea&gt;&gt; GetPickerItemsAsync(bool forceRefresh = false)
    {
        if (forceRefresh)
        {
            var json = await Client.GetStringAsync($&quot;api/servicearea&quot;);
            Servicesareas = await Task.Run(() =&gt; JsonConvert.DeserializeObject&lt;IEnumerable&lt;ServiceArea&gt;&gt;(json));
            try
            {
                var success = LocalDatabase.AddItemsAsync(Servicesareas);
                if (!success.Result)
                {
                    //Log de fallo en la insercion de datos.
                }
            }
            catch(AggregateException ae)
            {
               foreach (var e in ae.Flatten().InnerExceptions)
               {
                  Debug.WriteLine($&quot;{e.GetType().FullName} { e.Message}&quot;);
               }
            }
        }
        return Servicesareas;
    }

答案1

得分: 2

在你的 ServiceAreaStoreAPI 中,你没有等待一个任务,这可能是导致你的问题的原因,因为它会继续执行并返回一个已取消的结果。

var success = LocalDatabase.AddItemsAsync(Servicesareas);

英文:

In your ServiceAreaStoreAPI, you don't await a task which might be causing your issue since it'll continue on and return a canceled result.

var success = LocalDatabase.AddItemsAsync(Servicesareas);

答案2

得分: 0

如果您在方法体中使用了Task.Wait()方法,那么向方法添加async关键字将修复此问题。例如:

public async Task<ActionResult> Delete(int id) { }
英文:

If you have used the Task.Wait() method in the method body, then adding the async keyword to the method will fix this issue. Ex:

 public async Task&lt;ActionResult&gt; Delete(int id) { }

huangapple
  • 本文由 发表于 2020年1月7日 02:48:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/59617399.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定