c# - 在 .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();
}
}
解决方案
推荐阅读
- linux - 在脚本中采购 bashrc.user 时出现问题
- snowflake-cloud-data-platform - 无法提出支持案例
- c# - 将整个段落 InnerText 参数替换为新字符串。使用 OpenXML C#
- python - 将来自串口的传入数据转换为整数
- c# - 如何在 ValidationResult 中使用带有 mahapps.metro 和 wpflocalization 扩展的动态本地化?
- android - 无网络协程+改造时无异常/错误
- celery - 通过 Airflow 的 UI TriggerDag 参数指定 DAG 队列
- java - 无法弄清楚为什么 isLetterOrDigit 返回 true
- google-apps-script - 直接从表格访问已部署的应用脚本
- javascript - 通过 id 和类名获取元素来禁用文本框