锁定静态方法 [英] Lock in static methods

查看:63
本文介绍了锁定静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码:

public static class SomeClass
{
    private static List<Item> Items;

    //Constructor

    public static void AddToChache(string key, object item)
    {
        Items.Add(new Item(){ key = key , content = item, DateAdded = DateTime.Now});
    }

    public static List<Item> GetAllItems()
    {
        return Items;
    } 

    ....

如果要在应用程序级别创建缓存,此方法是否需要lock来处理并发?

If I want to create a cache in application level, does this methods need lock to handle concurrency?

我想使用线程安全的方法.

I want to thread-safe methods.

推荐答案

如果要在应用程序级别创建缓存,此方法是否需要锁定才能处理并发?

If I want to create a cache in application level, does this methods need lock to handle concurrency?

否,如果您改为使用线程安全集合,例如 ConcurrentDictionary ,否则是-它会.

No, if you use a thread safe collection instead, e.g. ConcurrentDictionary, otherwise yes - it does.

这篇关于锁定静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆