无法捕获异步/等待任务异常

时间:2017-03-08 10:43:50

标签: c# asynchronous async-await

我有一个消防方法(它的遗留目的),

BackgroundWorker.Run(() => {
          // my code here that throws an error                         
});

我不想等待BackgroundWorker.Run。这是我的班级,

public class BackgroundWorker
{        
    public static Task Run(Action action)
    {
        return new IISBackgroundTask().DoWorkAsync(action);
    }
    class IISBackgroundTask : IRegisteredObject
    {
        public IISBackgroundTask()
        {
            HostingEnvironment.RegisterObject(this);
        }            
        void IRegisteredObject.Stop(bool immediate)
        {
            if (_task.IsCompleted || _task.IsCanceled || _task.IsFaulted || immediate)
            {
                HostingEnvironment.UnregisterObject(this);
            }
        }
        public async Task DoWorkAsync(Action action)
        {
            try
            {
                _task =  Task.Run(action);
                await _task;
            }
            catch (AggregateException ex)
            {
                // Log exceptions
                foreach (var innerEx in ex.InnerExceptions)
                {
                    Logger.Log(innerEx);
                }
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
            }
        }

        private Task _task;
    }
}

我无法捕捉异常。

更新:如果我在BackgroundWorker.Run添加等待,那么它会起作用,但我想解雇并忘记。

1 个答案:

答案 0 :(得分:1)

现在我已经使用

修复了它
        public void DoWork(Action action)
        {
            _task = Task.Run(() => 
            {
                try
                {
                    action();
                }
                catch (AggregateException ex)
                {
                    foreach (var innerEx in ex.InnerExceptions)
                    {
                        Logger.Log(innerEx);
                    }
                }
                catch (Exception ex)
                {
                    Logger.Log(ex);
                }
            });
        }