【问题标题】:How can I get output results from my Queue<T> in C#?如何从 C# 中的 Queue<T> 获取输出结果?
【发布时间】:2014-03-18 17:04:15
【问题描述】:

我有两个线程,它们分别生成一系列图像。每个线程称为“line-1”和“line-2”。

我正在使用以下代码将其他两个线程的输出随机混合。然而,我期待从这个线程获得系列输出图像,但它没有给我任何输出。

    //thread 3
    private Bitmap RandomImageSelection()
    {
        Bitmap image;

        if (randomGenerator.Next(2) == 0 && line1.TryDequeue(out image))
        {
            return image;
        }

        if (line2.TryDequeue(out image))
        {
            return image;
        }

        pictureBox3.Image = image;

        return null;
    }

谁能告诉我如何从队列中的线程 3 获取一系列图像到我的图片框3?

【问题讨论】:

  • 您可能需要提供更多关于线程如何启动的代码才能获得有用的回复。带有图像的队列很可能尚未填充,因此,您无法将任何内容出列。所以你没有图像。
  • 你应该重新制定。如何设置你的图片框?
  • "RandomImageSelection" 可能应该在某种循环中,当两个线程都完成时终止。此外,您需要某种睡眠才能看到图像。
  • 其他重复问题的代码看起来更好 - 单个队列 - stackoverflow.com/questions/22484394/… 而不是 2 个队列
  • 也许你误解了我在stackoverflow.com/questions/22484394/… 的回答?

标签: c# image queue


【解决方案1】:

您的代码返回而不分配给图片框。它总是将 null 分配给 Picturebox。也许你应该重写它:

private Bitmap RandomImageSelection()
{
    Bitmap image = null;

    if (randomGenerator.Next(2) == 0 && !line1.TryDequeue(out image))
    {
        line2.TryDequeue(out image)
    }

    if (image != null) 
    {
        pictureBox3.Invoke(new Action(() => pictureBox3.Image = image));
    }

    return image;
}

在这种情况下,如果 line1 为空,它将从 line2 中选择,因此它将耗尽 line2。

编辑:添加了调用代码,因为这可能不在 UI 线程中执行。

【讨论】:

  • BlueM;谢谢你的评论;)这行给了我错误“if(image!= null)”,Error-1-Use of unassigned local variable 'image'
  • 只需在初始化程序中将 null 分配给位图。查看我的编辑。
【解决方案2】:

你没有设置图片到你的图片框

  Bitmap image;
  if ((randomGenerator.Next(2) == 0)? line1:line2).TryDequeue(out image))
  {
     pictureBox3.Image = image;
     return image;
  }
  return null;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-16
    • 2022-10-23
    • 1970-01-01
    • 2021-04-24
    • 2022-11-23
    • 2022-01-17
    相关资源
    最近更新 更多