C#LinkedList值不能为null

时间:2013-11-15 08:51:40

标签: c# multithreading linked-list

我有这个代码语句,我把它运行到一个计时器,它的间隔是50毫秒。 thread1工作后,我的链表(数据)等于Read_Data3。然后我检查这个条件if (data.ElementAt(0) == Convert.ToByte('$'))。但是它会出现“Value not not null”的错误。我检查过数组和链表不是空的。这个错误的原因是什么?有什么想法吗?

thread1 = new Thread(delegate()
{
    Read_Data2 = Read_Data1;
    lastCount = count;
    division = lastCount / 18;
    remaning = (lastCount - 18 * division);

    Read_Data3 = new byte[lastCount - remaning];

    for (int i = 0; i < lastCount - remaning; i++)
    {
        Read_Data3[i] = Read_Data2[i];
    }
    if (remaning > 0)
    {
        Read_Data4 = new byte[remaning];
        for (int i = 0; i < remaning; i++)
        {
            Read_Data4[i] = Read_Data2[lastCount - remaning + i];
        }
    }
    count = remaning;
    if (lastCount - remaning > 17)
    data = new LinkedList<byte>(Read_Data3);
});
    thread1.Start();

if (data.ElementAt(0) == Convert.ToByte('$'))
{
    for (int i = 0; i < (lastCount - remaning) / 18; i++)
    {
        //time = new XDate(DateTime.Now);
        if (data.ElementAt(0) == Convert.ToByte('$'))
        {
            data.Remove(data.ElementAt(0));
            for (int x = 0; x < 16; x++)
            {
                listAuido.Add(time, data.ElementAt(0));
                data.Remove(data.ElementAt(0));
            }
            listPulse.Add(time, data.ElementAt(0));
            data.Remove(data.ElementAt(0));
        }
        zgcMasterPane.AxisChange();
    }
    if (remaning > 0)
    {
        data2 = new LinkedList<byte>(Read_Data4);
        data2.Remove(data2.ElementAt(0));
        time = new XDate(DateTime.Now);
        for (int i = 0; i < remaning - 2; i++)
        {
            listAuido.Add(time, data2.ElementAt(0));
            data2.Remove(data2.ElementAt(0));
        }
    }
}

1 个答案:

答案 0 :(得分:1)

变量data设置在“线程方法”的末尾。

data = new LinkedList<byte>(Read_Data3);//<--assigned here

但调用此方法的线程不会等到thread1完成,所以你会在下一行得到ArgumentNullException

if (data.ElementAt(0) == Convert.ToByte('$'))

要解决此问题,您可能需要等到thread1完成。

thread1.Start();
thread1.Join();

或者只是从线程委托中的if语句中移动以下代码。