在.NET 4和WebForms中异步处理批处理请求回调

时间:2018-06-19 08:50:21

标签: c# .net webforms batch-request

在示例中,您可以看到我在按钮单击时执行批量请求。之后,我需要使用回调中提供的信息,但不要冻结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();

使用Thread的方法:

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();
    }
}

0 个答案:

没有答案