为什么在 C# 中 Queue 会扰乱其元素中的数据?

2024-01-02

我对我的队列的功能完全感到困惑。我正在尝试(但失败了)写 一个小型多线程应用程序,用于用 C# 收集和显示数据。
读完后阿尔巴哈里的书 http://www.albahari.com/threading/并使用消费者/生产者 他描述的模式我大部分都可以工作,除了我的数据似乎被扰乱了 队列。在排队之前,我的对象中的字段具有以下值

时间戳 = 6
数据[] ={4936, 9845, 24125, 44861}

出队后数据看起来像

时间戳 = 6
数据[] = {64791, 19466, 47772, 65405}

我不明白为什么数据字段中的值在出队后会发生变化? 我很困惑,所以我想我应该把它扔在那里,看看是否有人能给我指出正确的方向来解决这个问题,或者为我指出一个不同的方向来继续。


相关代码


用于数据存储的自定义对象

相关对象和字段。类传感器数据是一个单独的类,用于存储我的计算。

public class sensorData
{
    public const int bufSize = 4;
    public UInt16[] data = new UInt16[4];
    public double TimeStamp = 0; 
    public int timeIndex = 0;
}

以下字段用于设置队列以及入队和出队线程之间的信号。

EventWaitHandle wh = new AutoResetEvent(false);
Queue<sensorData> dataQ = new Queue<sensorData>();
object locker = new object();

入队方法/线程

这是我的工作线程,它计算四个正弦曲线并将结果排队进行处理。 我还将结果写入文件,以便我知道它计算了什么。

private void calculateAndEnqueueData(BackgroundWorker worker, DoWorkEventArgs e)
{
    int j = 0;
    double time = 0;
    double dist;
    UInt16[] intDist = new UInt16[sensorData.bufSize];
    UInt16 uint16Dist;

    // Frequencies of the four Sine curves
    double[] myFrequency = { 1, 2, 5, 10 };

    // Creates the output file.
    StreamWriter sw2 = File.CreateText("c:\\tmp\\QueuedDataTest.txt"); 

    // Main loop to calculate my Sine curves
    while (!worker.CancellationPending)
    {
        // Calculate four Sine curves
        for (int i = 0; i < collectedData.numberOfChannels; i++)
        {
            dist = Math.Abs(Math.Sin(2.0 * Math.PI * myFrequency[i] * time);
            uint16Dist = (UInt16)dist;
            intDist[i] = uint16Dist;
        }

        // Bundle the results and Enqueue them
        sensorData dat = new sensorData();
        dat.data = intDist;
        dat.TimeStamp = time;
        dat.timeIndex = j;

        lock (locker) dataQ.Enqueue(dat);
        wh.Set

        // Output results to file.
        sw2.Write(j.ToString() + ", ");
        foreach (UInt16 dd in dat.intData)
        {
            sw2.Write(dd.ToString() + ", ");
        }
        sw2.WriteLine();

        // Increments time and index.
        j++;
        time += 1 / collectedData.signalFrequency;

        Thread.Sleep(2);
    }
    // Clean up
    sw2.Close();
    lock (locker) dataQ.Enqueue(null);
    wh.Set();
    sw2.Close();
}

输出文件中的示例行排队数据测试.txt

6、4936、9845、24125、44861、

数据出队方法

此方法将元素从队列中出列并将它们写入文件。直到在队列中找到空元素为止,此时工作就完成了。

    private void dequeueDataMethod()
    {
        StreamWriter sw = File.CreateText("C:\\tmp\\DequeueDataTest.txt");

        while (true)
        {
            sensorData data = null;

            // Dequeue available element if any are there.
            lock (locker)
                if (dataQ.Count > 0)
                {
                    data = dataQ.Dequeue();
                    if (data == null)
                    {
                        sw.Close();
                        return;
                    }
                }

            // Check to see if an element was dequeued. If it was write it to file.
            if (data != null)
            {
                sw.Write(data.timeIndex.ToString() + ", ");
                foreach (UInt16 dd in data.data)
                    sw.Write(dd.ToString() + ", ");
                sw.WriteLine();
            }
            else
            {
                wh.WaitOne();
            }
        }

将数据出队并写入后输出结果出队数据测试.txt

6、64791、19466、47772、65405、


更新1:

当前代码中锁的位置。


我已经编辑了代码以在将数据写入文件的过程中放置​​锁。所以我加锁的代码块如下。

In the 计算并入队数据()我有的方法

lock (locker) dataQ.Enqueue(dat);
wh.Set

lock(locker)
{
  sw2.Write(j.ToString() + ", ");
  foreach (UInt16 dd in dat.intData)
  {
     sw2.Write(dd.ToString() + ", ");
  }
  sw2.WriteLine();
}

In the 出队数据方法()我有两个带锁的区域,第一个区域在这里

lock(locker) 
    if (dataQ.Count > 0)
    {
       data = dataQ.Dequeue();
       if (data == null)
       {
           sw.Close();
           return;
        }
    }

我假设锁定储物柜中的代码if堵塞。第二个是我将其写入文件的位置

lock (locker)
{
    sw.Write(data.timeIndex.ToString() + ", ");
    foreach (UInt16 dd in data.intData)
        sw.Write(dd.ToString() + ", ");
    sw.WriteLine();
    if (icnt > 10)
    {
        sw.Close();
        return;
    }
    this.label1.Text = dataQ.Count.ToString();
}

这就是他们的全部。



该问题是由于您正在写入的 StreamWriter 上没有同步造成的。顺序不是连续的。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么在 C# 中 Queue 会扰乱其元素中的数据? 的相关文章

随机推荐