【发布时间】:2016-06-27 13:20:22
【问题描述】:
在我的 api (c#) 中,我目前正在回答很多请求(15-20 秒)。现在我想出于某些目的将数据发送到事件中心。但我不想延迟用户将数据发送到 azure 事件中心。所以我需要向事件中心发出异步请求,因为当我的应用程序将数据发送到天蓝色时,我不想让用户等待我的回答。我需要尽快发送响应,azure 可能会持续 2-3 秒。
我怎样才能成功? 我做了什么,但没有得到我想要的。我的代码:
public static async Task<string> SendEvents(List<object> messages)
{
string eventHubName = "rcmds";
var connectionString = GetServiceBusConnectionString();
CreateEventHub(eventHubName, connectionString);
var eventHubClient = EventHubClient.CreateFromConnectionString(connectionString, eventHubName);
try
{
List<Task> tasks = new List<Task>();
for (int i = 0; i < messages.Count; i++)
{
var serializedMessage = JsonConvert.SerializeObject(messages[i]);
EventData data = new EventData(Encoding.UTF8.GetBytes(serializedMessage));
// Mesajları Event Hub a yolla
tasks.Add(eventHubClient.SendAsync(data));
}
Task.WaitAll(tasks.ToArray());
System.Threading.Thread.Sleep(7000);
}
catch (Exception ex)
{
new ExceptionHandler(ex, "Event Hub Library Sender - SendEvents");
}
finally
{
eventHubClient.CloseAsync().Wait();
}
return "";
}
我把这个方法称为:
static async void method()
{
List<object> list = new List<object>();
list.Add("dogrudur");
await Utilities.EventHub.Sender.SendEvents(list);
}
如您所见,有“thread.sleed”代码但我等了 7 秒:/
【问题讨论】:
标签: c# azure asynchronous asp.net-web-api azure-eventhub