直接上圖,帮忙分析下代码

zsyok 2016-07-22 03:19:00

为什么List 里面会出现null 的??
...全文
201 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
tianlang_2008 2016-07-22
  • 打赏
  • 举报
回复
因为你开启线程的操作是异步的。
正怒月神 2016-07-22
  • 打赏
  • 举报
回复
使用 ConcurrentBag<T> 因为List<T>是非线程安全的
mjp1234airen4385 2016-07-22
  • 打赏
  • 举报
回复
我测试你的代码,没发现你说的问题啊。
zsyok 2016-07-22
  • 打赏
  • 举报
回复
引用 2 楼 sp1234 的回复:
对于源,要上代码,不要上图。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    public class Program
    {
        private static List<LOCK> LockList = new List<LOCK>();
        public class LOCK
        {
            public LOCK(int uid, DateTime t)
            {
                UserId = uid;
                PostTime = t;
            }
            public long UserId { get; set; }
            public DateTime PostTime { get; set; }
        }
        static List<Thread> threads = new List<Thread>();
        static Random ran = new Random();
        static void Main(string[] args)
        {
            for (int i = 0; i < 99; i++)
            {
                Thread xx = new Thread(new ThreadStart(str));
                xx.Start();
                threads.Add(xx);
            }
            Console.WriteLine(11111);
        }
        private static void str()
        {
            while (true)
            {
                int id = ran.Next(1000000, 9000000);
                LockList.Add(new LOCK(id, DateTime.Now));
                System.Threading.Thread.Sleep(10);
                LockList.RemoveAll(x => x.UserId == id);
            }
        }
    }

}

大哥,有什麼办法解决。
zsyok 2016-07-22
  • 打赏
  • 举报
回复
引用 1 楼 Forty2 的回复:
因为List<LOKCK> LockList 不是线程安全的。
有时候还有异常: 由于线程停在某个无法进行垃圾回收的点(可能是因为已对代码进行了优化),因此无法计算表达式的值 具体有什么解决方法?
  • 打赏
  • 举报
回复
对于源,要上代码,不要上图。
Forty2 2016-07-22
  • 打赏
  • 举报
回复
因为List<LOKCK> LockList 不是线程安全的。

110,533

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧