执行异步方法时,UWP应用程序崩溃

时间:2019-01-11 15:18:43

标签: exception uwp async-await crash mvvm-light

我在BaseViewModel(MVVMLight应用程序)中创建了两个方法,以使用某种逻辑来执行任何异步代码:

    public async Task PerformOperation(Func<Task> action)
    {
        IsBusy = true;

        try
        {
            await action?.Invoke();
        }
        catch(Exception ex)
        {
            // logging is here
        }
        finally
        {
            IsBusy = false;
        }
    }

    public async Task PerformOperation(params Operation[] actions)
    {
        IsBusy = true;
        MultipleOperatrions = true;
        OperationStatuses = new ObservableCollection<OperationStatus>();

        try
        {
            foreach(var action in actions)
            {
                var status = new OperationStatus() { StatusText = action.StatusText };
                OperationStatuses.Add(status);

                try
                {
                    await action?.AsyncAction();
                    status.Success = true;
                }
                catch
                {
                    status.Success = false;
                }
                finally
                {
                    status.IsFinished = true;
                }
            }
        }
        catch (Exception ex)
        {
            // logging is here
        }
        finally
        {
            await Task.Delay(1000);

            IsBusy = false;
            MultipleOperatrions = false;
            OperationStatuses = new ObservableCollection<OperationStatus>();
        }
    }

我的模特:

public class Operation
{
    public Func<Task> AsyncAction { get; private set; }

    public string StatusText { get; private set; }

    public Operation(Func<Task> action, string statusText)
    {
        AsyncAction = action;
        StatusText = statusText;
    }
}

我在视图模型中调用方法的代码:

    ...
    private IAsyncCommand _buildCommand;
    public IAsyncCommand BuildCommand => _buildCommand ?? (_buildCommand = new AsyncCommand(Build));

    #endregion

    #region Methods

    public async Task Build()
    {
        // IT WORKS
        // this method is used for performing only a single operation
        // await PerformOperation(async () => { await Task.Delay(3000); });

        // IT CRASHES THE APP
        // for many tasks
        await PerformOperation(new Operation(async () => { await Task.Delay(3000); }, "Preparing..."));
    }
    ...

因此,如果我调用PerformOperation仅调用一个方法-它将很好地工作。但这不是执行多种操作的方法-应用程序崩溃时没有任何异常或消息。我在App.cs中订阅了UnhandledException事件以捕获该事件,但该应用只是崩溃了。

0 个答案:

没有答案