在同步逻辑块的良好实践中为异步方法添加'await'吗?

时间:2017-12-13 01:03:04

标签: c# asp.net-mvc asynchronous async-await

Asp.Net MVC中的synchronous网站(获取,显示成功,上传,显示成功等等),但我确实有一个async方法来调用以发送消息给我的Azure服务总线队列,稍后由Azure函数触发。

当我调用asynchronous方法将消息放在Azure队列上时,我想将返回的序列保存在我的数据库中,以便我可以在以后取消该消息(如果需要)。但据我所知,我不应该等待async方法,特别是因为我需要相当快地向用户显示成功。那么下面的代码运行async方法是执行此类操作的最佳方法吗? AFAIK'await'将等到返回值返回,我应该在返回控制器并查看之前这样做吗?

  

ScheduleMessageAsync

此代码是我的控制器调用的服务类的一部分

internal void SaveEvent(some parameters) {
    // save event details in db
    // now call up class to save message into the Azure queue
    MessageQueue messageQueue = new MessageQueue();
    messageQueue.SendMessage(eventId);

    // do some other stuff like send the user a email and return to the controller and show the user his/her new event has been saved
}

现在,我有消息代码将消息保存在Azure队列中

public async void SendMessage(int eventId)
{
    string serviceBusConnectionString = System.Configuration.ConfigurationManager.AppSettings["ServiceBusConnectionString"];
    string queueName = System.Configuration.ConfigurationManager.AppSettings["QueueName"];

    var queueClient = QueueClient.CreateFromConnectionString(serviceBusConnectionString, queueName); 

    BrokeredMessage message = new BrokeredMessage("some test message");
    message.MessageId = eventId.ToString();

    ////newEvent.EventDateTime
    // TimeSpan ts = new TimeSpan(1, 0, 0);
    // DateTimeOffset dto = new DateTimeOffset(DateTime.Now, ts);
    long sequenceToCancel = await queueClient.ScheduleMessageAsync(message, DateTimeOffset.Now.AddDays(6));

    queueClient.Close();

    // store sequenceToCancel in db table
}

0 个答案:

没有答案