2017-03-08 54 views
0

我有火和忘記方法(它是爲傳統用途),無法趕上異步/ 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等待,那麼它會工作,但我想火,忘了。

+0

哪一種例外的,你能不能請張貼異常信息? – KimKulling

+0

@KimKulling在'//我的代碼在這裏拋出一個錯誤'的空異常' – user960567

+0

「Fire and ** forget **」字面意思*表示*「我不在乎異常」。 –

回答

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