我已经被困了一段时间了,我希望有人能帮助我。我正在尝试从 Azure 的 EventHub 接收数据,并使用 MVC 在 ASP.NET 页面上(实时)显示这些数据。
我找到了一种方法来创建一个等待接收事件的异步方法,我每秒用 jQuery 刷新这个方法和部分视图,但我发现随着时间的推移这给了我太多的不稳定性,它会以无限循环结束的错误。
这是我的代码:
public async Task<ActionResult> Index()
{
time = DateTime.Now;
list = new List<TestEntity>();
TestEntity t = new TestEntity();
list.Add(t);
await Initialize();
return View(list);
}
public async Task<ActionResult> RefreshLatest()
{
try
{
var message = await consumer.ReceiveAsync();
if (message != null)
{
TestEntity t = JsonConvert.DeserializeObject<TestEntity>(Encoding.UTF8.GetString(message.GetBytes()));
list.Add(t);
}
}
catch (Exception exception)
{
Console.WriteLine("exception on receive {0}", exception.Message);
}
return PartialView("Latest", list);
}
private static async Task Initialize()
{
EventHubClient eventHubClient = getEventHubClient(SharedAccessKeyName, SharedAccessKey, NamespaceURI, EventHubName, ConnectionString);
EventHubConsumerGroup consumerGroup = eventHubClient.GetDefaultConsumerGroup();
consumer = await consumerGroup.CreateReceiverAsync(partitionId, DateTime.Now, receiverEpoch); // All messages
}
public static EventHubClient getEventHubClient(string SharedAccessKeyName, string SharedAccessKey, string NamespaceURI, string EventHubName, string ConnectionString)
{
//Create EventHub
TokenProvider td = TokenProvider.CreateSharedAccessSignatureTokenProvider(SharedAccessKeyName, SharedAccessKey);
NamespaceManager manager = new NamespaceManager(NamespaceURI, td);
var description = manager.CreateEventHubIfNotExists(EventHubName);
//Create EventHubClient
EventHubClient client = EventHubClient.CreateFromConnectionString(ConnectionString + ";EntityPath=" + EventHubName);
return client;
}
这是我的索引视图:
http://puu.sh/gDQUj/cb816b8870.png
我希望你能看到我想要完成的事情以及它是如何失败的。