如何刷新部分视图异步/等待Azure事件中心?

时间:2015-03-17 08:34:55

标签: c# jquery asp.net async-await azure-eventhub

我已经被困在案件上一段时间了,我希望有人可以帮助我。 我试图从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

我希望你能看到我想要完成的事情以及失败的原因。

0 个答案:

没有答案