2

dotnet C# 多线程集合的 Linq 获取值同时写入集合将会抛出异常

 3 years ago
source link: https://lindexi.gitee.io/post/dotnet-C-%E5%A4%9A%E7%BA%BF%E7%A8%8B%E9%9B%86%E5%90%88%E7%9A%84-Linq-%E8%8E%B7%E5%8F%96%E5%80%BC%E5%90%8C%E6%97%B6%E5%86%99%E5%85%A5%E9%9B%86%E5%90%88%E5%B0%86%E4%BC%9A%E6%8A%9B%E5%87%BA%E5%BC%82%E5%B8%B8.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
dotnet C# 多线程集合的 Linq 获取值同时写入集合将会抛出异常

在集合变更,无论是使用 foreach 遍历还是使用 Linq 语句,即使是 FirstOrDefault 获取第一项,都会失败

例如下面代码,在两个线程里面,第一个线程获取使用 FirstOrDefault 方法,第二个线程变更集合内容

        static void Main(string[] args)
        {
            var list = new List<string>();
            Task.Run(() =>
            {
                while (true)
                {
                    var str = list.FirstOrDefault();
                    Console.WriteLine(str);
                }
            });

            Task.Run(() =>
            {
                while (true)
                {
                    list.Clear();
                    list.Add("doubi");
                }
            });

            Console.Read();
        }

运行以上代码,可以看到抛出了 ArgumentOutOfRangeException 如下面代码

System.ArgumentOutOfRangeException:“Index was out of range. Must be non-negative and less than the size of the collection. ”

本文所有代码放在 githubgitee 欢迎小伙伴访问

可以通过如下方式获取本文的源代码,先创建一个空文件夹,接着使用命令行 cd 命令进入此空文件夹,在命令行里面输入以下代码,即可获取到本文的代码

git init
git remote add origin https://gitee.com/lindexi/lindexi_gd.git
git pull origin ffc985358957cc0c06c0985caa1d166c7ef8757d

以上使用的是 gitee 的源,如果 gitee 不能访问,请替换为 github 的源

git remote remove origin
git remote add origin https://github.com/lindexi/lindexi_gd.git

获取代码之后,进入 GujidearkiLicairfeeka 文件夹


本文会经常更新,请阅读原文: https://blog.lindexi.com/post/dotnet-C-%E5%A4%9A%E7%BA%BF%E7%A8%8B%E9%9B%86%E5%90%88%E7%9A%84-Linq-%E8%8E%B7%E5%8F%96%E5%80%BC%E5%90%8C%E6%97%B6%E5%86%99%E5%85%A5%E9%9B%86%E5%90%88%E5%B0%86%E4%BC%9A%E6%8A%9B%E5%87%BA%E5%BC%82%E5%B8%B8.html ,以避免陈旧错误知识的误导,同时有更好的阅读体验。

如果你想持续阅读我的最新博客,请点击 RSS 订阅,推荐使用RSS Stalker订阅博客,或者前往 CSDN 关注我的主页

本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。欢迎转载、使用、重新发布,但务必保留文章署名林德熙(包含链接: https://blog.lindexi.com ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请 与我联系

无盈利,不卖课,做纯粹的技术博客

以下是广告时间

推荐关注 Edi.Wang 的公众号
lindexi%2F201985113622445

欢迎进入 Eleven 老师组建的 .NET 社区
lindexi%2F20209121930471745.jpg

以上广告全是友情推广,无盈利


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK