【发布时间】:2023-03-18 16:34:01
【问题描述】:
我发现几个答案抨击以异步方式使用会话状态,例如。
在某些情况下从异步线程更新会话将不会或无法工作?
我的用例如下:
在应用程序中,用户个人资料数据存储在会话中。旨在在管理员更改用户名、群组或其他个人资料信息等时异步刷新个人资料数据。
异步推力: 轮询存储数据已更改的用户 ID 的数据库表。 如果数据与当前用户 id 匹配,则刷新配置文件数据,从表中删除 id
我发现以下代码异步更新会话密钥。
public class MyAsyncUpdateController : Controller
{
public static string MyKey = "myKey";
public ActionResult Index()
{
Session[MyKey] = "Init Data: Updated at " + DateTime.Now.TimeOfDay;
Task.Factory.StartNew(session =>
{
Thread.Sleep(10000);
var _session = (HttpSessionState)session;
if (_session != null)
_session[MyKey] = "Async Data: Updated at " + DateTime.Now.TimeOfDay ;
}, System.Web.HttpContext.Current.Session);
return RedirectToAction("OtherAction");
}
public ActionResult OtherAction()
{
string result = "";
if (Session != null && Session[MyKey] != null)
result= Session[MyKey].ToString();
return Content(result);
//Refresh until see updated timestamp
}
}
在从异步任务写入会话数据时,是否还有其他注意事项或保护措施(除了空检查)?
【问题讨论】:
标签: c# session asynchronous task-parallel-library