首页 > 解决方案 > 在 .NET 4 和 WebForms 中异步处理批处理请求回调

问题描述

在示例打击中,您可以看到我在单击按钮时执行批处理请求。之后我需要使用回调中提供的信息,但不会冻结 WebForms 页面。我认为回调本身是异步的,但显然我错了,因为在未处理回调之前页面保持冻结状态。

batchRequest.Queue<Google.Apis.Calendar.v3.Data.Event>(
    addRequest,
    (content, error, i, message) =>    // callback
    {
        using (dbContext)
        {
            Event eventToUpdate = dbContextNewInstance.Events.FirstOrDefault(x => x.Id == dbObj.Id);
            if (eventToUpdate != null)
            {
                eventToUpdate.GoogleCalendarMappingId = content.Id;
                dbContextNewInstance.SubmitChanges();
            }
        }
    });

batchRequest.ExecuteAsync();

*更新:我已经完成了这个实现并且它的工作!到目前为止,我担心一切都在正确的方向上进行,没有线程或数据库连接不受管理,伙计们?

batchRequest.Queue<Google.Apis.Calendar.v3.Data.Event>(
                                 addRequest,
                                 (content, error, i, message) =>    // callback
                                 {
                                     idsToMap[dbObj.Id] = content.Id; // A dictionary for my dbObj Id and the Id I receive from the remote API in the CALLBACK
                                 });


                Thread batchThread = new Thread(() => SubmitBatchRequest(batchRequest, idsToMap, connectionString));
            batchThread.Start();

以及带有线程的方法:

private static void SubmitBatchRequest(BatchRequest batchRequest, Dictionary<Guid, string> ids, string connectionString)
{
    Thread.CurrentThread.IsBackground = true;

    batchRequest.ExecuteAsync().GetAwaiter().GetResult(); // Send the batch request asynchronous

    using (DataContext db = new DataContext(connectionString))
    {
        foreach (Guid dbObjId in ids.Keys)
        {
            Event eventToUpdate = db.Events.FirstOrDefault(x => x.Id == dbObjId);
            if (eventToUpdate != null)
            {
                eventToUpdate.GoogleCalendarMappingId = ids[dbObjId];
            }
        }

        // Thread.Sleep(50000);
        db.SubmitChanges();
    }
}

标签: c#.netwebformsbatch-request

解决方案


推荐阅读