获得一个将数据保存到数据库的void函数,一旦数据被保存,我试图调用一个函数来发送推送通知,它应该运行 async 但事实并非如此。我做错了什么?
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 :(得分:0)
Stephen Cleary在blog中广泛涵盖了如何不使用Task.Run
。
由于您不想等待异步回调完成,您当然可以启动另一个线程并完全忘记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);
}
}
答案 1 :(得分:-2)
尝试此操作以发送通知:
Task.Run(() => SendRaisedTicketNotifications(m)).Wait();