同时使用httpcontext.items

时间:2019-05-15 11:24:01

标签: c# concurrency asp.net-core-2.1

_httpcontextAccessor.HttpContext.UpdateAskDate(askDate);


 public static void UpdateAskDate(this HttpContext context, DateTime AskDate) => context.Items["AskDate"] = AskDate;

要存储某个日期,当我有一个查询时,_httpcontextAccessor像一个单例一样注册,但是我总是遇到此错误,您对为什么有任何想法吗?

     GraphQL.ExecutionError: Error trying to resolve header. ---> System.InvalidOperationException: Operations that change non-concurrent collections must have exclusive access. A concurrent update was performed on this collection and corrupted its state. The collection's state is no longer correct.
   at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior)
   at System.Collections.Generic.Dictionary`2.set_Item(TKey key, TValue value)

致谢

1 个答案:

答案 0 :(得分:0)

这里的上下文有点不清楚,但是如果您同时从多个线程调用UpdateAskDate,似乎您应该同步对Items集合的访问。例如,您可以使用lock语句来完成此操作:

private static readonly object s_lock = new object();
public static void UpdateAskDate(this HttpContext context, DateTime AskDate)
{
    lock (s_lock) //only allow one thread at a time to enter here
        context.Items["AskDate"] = AskDate;
}

请注意,您需要对context.Items的所有访问使用相同的锁。