簡體   English   中英

如何使用 ContinueWith 和 WhenAll 處理異常?

[英]How to handle exceptions with ContinueWith and WhenAll?

我正在嘗試異步加載多個文件,並在每個文件加載完成時通知 UI,

_loadCancellationTokenSource = new CancellationTokenSource();

TaskScheduler scheduler = TaskScheduler.FromCurrentSynchronizationContext();
var files = await picker.PickMultipleFilesAsync();
LoadedFiles.Clear();

loads = await Task.WhenAll(files.Select(file =>
{
    var load = LoadAsync(file);
    load.ContinueWith(t =>
    {
        if (t.IsCompleted) LoadedFiles.Add(file.Path);
        if (t.IsFaulted) NotifyUser(t.Exception.Message, NotifyType.ErrorMessage);
        if (t.IsCanceled) NotifyUser("operation was canceled.", NotifyType.ErrorMessage);
    }, scheduler);
    return load;
}));

private Task<Foo> LoadAsync(StorageFile file)
{
    // exception may be thrown inside load
    return Load(file, _loadCancellationTokenSource.Token);
}

問題是當拋出異常時,它沒有被處理。 我知道為什么,因為ContinueWith創建了一個新任務,但我返回了舊任務。

這是因為ContinueWith是一項無效任務。 但我不知道如何正確返回結果。 我不確定使用t.Result是否安全,因為它可能會阻塞 UI 線程?


PS,我已經嘗試過這段代碼,但即使我沒有取消任何任務,我也收到a task was cancelled exception和應用程序崩潰的消息。 加載某些文件時只會拋出一些異常。

load = (await Task.WhenAll(files.Select(file =>
{
    var load = LoadAsync(file);
    load.ContinueWith(t =>
    {
        if (t.IsFaulted) NotifyUser(t.Exception.Message, NotifyType.ErrorMessage);
        if (t.IsCanceled) NotifyUser("operation was canceled.", NotifyType.ErrorMessage);
    }, _loadCancellationTokenSource.Token, TaskContinuationOptions.NotOnRanToCompletion, scheduler);
    return load.ContinueWith(t =>
    {
        LoadedFiles.Add(file.Path);
        return (file, t.Result);
    }, _loadCancellationTokenSource.Token, TaskContinuationOptions.OnlyOnRanToCompletion, scheduler); ;
})));

感謝@Jimi,我能夠通過查看任務狀態來解決這個問題。

loads = (await Task.WhenAll(files.Select(file =>
{
    return LoadAsync(file).ContinueWith(t =>
    {
        if (t.IsFaulted) NotifyUser(t.Exception.Message, NotifyType.ErrorMessage);
        if (t.IsCanceled) NotifyUser("operation was canceled.", NotifyType.ErrorMessage);

        if (t.Status == TaskStatus.RanToCompletion)
        {
            LoadedFiles.Add(file.Path);
            return t.Result;
        }

        return null;
    }, scheduler);
}))).Where(x => x != null).ToArray();

暫無
暫無

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

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