2017-08-02 48 views
0

得到一個無效函數,將數據保存到數據庫,一旦數據被保存我正試圖調用一個函數,它將發送推送通知,它應該是運行的async但它沒有。我究竟做錯了什麼?在void C中調用一個異步方法#

public void Save(MyModel m) 
    { 
     using (var conn = Databases.DB) 
     { 
      var d = new DynamicParameters(new 
      { 
       m.Name 
      }); 

      conn.Execute("INTRANET__CreateTicket", d, commandType: CommandType.StoredProcedure); 

      //send push notifications 
      Task.Run(() => SendRaisedTicketNotifications(m)); 

     } 
    } 

    private async void SendRaisedTicketNotifications(NewAmbercatTicketView t) 
    { 
     await Task.Run(() => 
     { 
      //Send push notifications 
      var sub = new Subscritption(); 

      var people = UserRepository.List(); 
      foreach (var person in people) 
      foreach (var sub in UserPushRepository.List().Where(x => x.PersonId == person.PersonId && x.Subscribed)) 
      { 
       var notification = new PushNotification("Some content") 
       notification.SendPushNotification(sub); 
      } 
     }); 
    } 
+0

'async void'是一種不好的做法。使用'異步任務'而不是 –

+2

出現兩次的'Task.Run'應該已經響起了警鐘。我也想知道爲什麼SendRaisedTicketNotifications看起來完全不依賴於它的參數。 –

+1

你究竟想在這裏發生什麼?你只是試圖同步調用方法,或者你想將它作爲後臺任務來運行嗎?我不確定你知道異步實際意味着什麼。 – DavidG

回答

-2

嘗試使用此方法發送您的通知:

Task.Run(() => SendRaisedTicketNotifications(m)).Wait(); 
+1

這將不會運行異步,而是阻塞線程,直到任務完成。 – Adwaenyth

+0

不會導致死鎖 –

+0

但他問,如何在void中調用一個異步方法。這是我知道的唯一方法... –

0

如何不使用Task.Run由斯蒂芬·克利裏相當廣泛在他blog覆蓋。

由於您不想等待異步回調完成,因此您當然可以啓動另一個線程並忘記約Task.Run,因爲您無法實際使用該任務。

public void Save(MyModel m) 
{ 
    using (var conn = Databases.DB) 
    { 
     var d = new DynamicParameters(new 
     { 
      m.Name 
     }); 

     conn.Execute("INTRANET__CreateTicket", d, commandType: CommandType.StoredProcedure); 

     //send push notifications in BackgroundThread 
     Thread sendInBackground = new Thread(new ParametrizedThreadStart(SendRaisedTicketNotifications)); 
     sendInBackground.IsBackground = true; 
     sendInBackground.Start(m); 

    } 
} 

private void SendRaisedTicketNotifications(NewAmbercatTicketView t) 
{ 
    //Send push notifications 
    var sub = new Subscritption(); 

    var people = UserRepository.List(); 
    foreach (var person in people) 
    foreach (var sub in UserPushRepository.List().Where(x => x.PersonId == person.PersonId && x.Subscribed)) 
    { 
     var notification = new PushNotification("Some content") 
     notification.SendPushNotification(sub); 
    } 
}