Unable to catch async/await Task exception

I have a fire and forget method(its there for legacy purpose),

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

I don't wanna await BackgroundWorker.Run. Here is my class,

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;
    }
}

I am unable to catch exception.

Update: If I add await at BackgroundWorker.Run then it will work but I wanna fire and forget.

Upvotes: 0

Views: 169

Answers (1)

For now I have fixed it using,

        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);
                }
            });
        }

Upvotes: 1

Related Questions