Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 通过静态方法在asp.net会话中存储和更新列表是否安全?_C#_Asp.net_Thread Safety - Fatal编程技术网

C# 通过静态方法在asp.net会话中存储和更新列表是否安全?

C# 通过静态方法在asp.net会话中存储和更新列表是否安全?,c#,asp.net,thread-safety,C#,Asp.net,Thread Safety,下面的代码是线程安全的吗?如果没有,请您建议正确的方法如何使其线程安全?我只是想避免锁,如果它是多余的 public static IList<string> Urls => urlList; public static bool AddUrl(string url) { var list = urlList; if (list.Contains(url)) { return true; } list.Add(url); urlList =

下面的代码是线程安全的吗?如果没有,请您建议正确的方法如何使其线程安全?我只是想避免锁,如果它是多余的

public static IList<string> Urls => urlList;

public static bool AddUrl(string url)
{
  var list = urlList;
  if (list.Contains(url))
  {
    return true;
  }

  list.Add(url);
  urlList = list;
  return false;
}

private static IList<string> urlList
{
  get
  {
    List<string> list = null;
    var sessionValue = HttpContext.Current.Session[sessionKey];
    if (sessionValue != null)
    {
      list = sessionValue as List<string>;
    }

    if (list == null)
    {
      list = new List<string>();
    }

    return list;
  }
  set
  {
    HttpContext.Current.Session[sessionKey] = value;
  }
}
公共静态IList URL=>urlList;
公共静态bool AddUrl(字符串url)
{
var list=urlist;
if(list.Contains(url))
{
返回true;
}
列表。添加(url);
urlList=列表;
返回false;
}
私有静态IList URL列表
{
收到
{
List=null;
var sessionValue=HttpContext.Current.Session[sessionKey];
if(sessionValue!=null)
{
列表=作为列表的sessionValue;
}
if(list==null)
{
列表=新列表();
}
退货清单;
}
设置
{
HttpContext.Current.Session[sessionKey]=值;
}
}

线程安全是您最不关心的问题<代码>静态
变量在会话间共享。您可能正在与其他用户共享应该驻留在用户上下文中的信息(因为您将其存储在会话中而不是应用程序缓存中)


为了线程安全,我确实会引入锁。手动启动新线程时,还有一件事可能会导致问题:HttpContext.Current.Session在该线程中不可用,因为它特定于请求运行的线程。

是否最好在AddUrl方法中添加锁?是的,第一个调用
包含
。如果为false,则锁定,再次检查
包含
,如果仍然为false,则添加。