c#:线程不工作

时间:2012-12-19 06:59:59

标签: c# multithreading

我希望在转换器处理时显示GIF图像。但是GIF图像从不显示显示,并且转换器过程成功完成,同时花费大约20秒,因此图片框是空白的。 如果我用MessageBox.Show替换转换器进程,GIF图像和Message.Show都能正常工作。

我需要做什么?

Thread th = new Thread((ThreadStart)delegate                  
{
    pictureBox1.Image = Image.FromFile("loading_gangnam.gif");                                 
    Thread.Sleep(5000);
});

th.Start(); 

//MessageBox.Show("This is main program");
Converted = converter.Convert(input.FullName, output);

4 个答案:

答案 0 :(得分:3)

UI的绘制是在绘制事件期间完成的,只有在代码完成任何想法时才会处理它。

此外,您当前的代码已损坏。您应该从不操作工作线程中的UI控件(例如PictureBox)。这导致“检测到跨线程操作”(或类似)异常。

选项:

  • 处理图像的一部分,然后让它绘画,并安排计时器或其他事件以暂时继续绘图
  • 隔离(非UI)图片上的后台线程上进行工作,定期对当前工作图像进行复制,并使用{{1}将副本设置为图片框的内容。

还有一种明确的方法可以在UI循环中处理事件,但是真的不好的做法,我甚至无法通过名称提及它。

答案 1 :(得分:1)

您正在从主UI线程以外的其他线程访问表单控件。 您需要使用Invoke()。

请参阅here以获取示例

答案 2 :(得分:1)

你的线程倒退了。您希望UI线程立即显示GIF,但转换为在新线程上运行。应该是这样的:

Thread th = new Thread((ThreadStart)delegate                  
{
    Converted = converter.Convert(input.FullName, output);
});
th.Start(); 

// should probably check pictureBox1.InvokeRequired for thread safety
pictureBox1.Image = Image.FromFile("loading_gangnam.gif");   

进一步阅读: http://msdn.microsoft.com/en-us/library/3s8xdz5c.aspx http://msdn.microsoft.com/en-us/library/ms171728.aspx

答案 3 :(得分:0)

尝试此功能设置loading_gangnam.gif图像:

public void newPicture(String pictureLocation)
{
    if (InvokeRequired)
    {
        this.Invoke(new Action<String>(newPicture), new object[] { pictureLocation });
    }
    pictureBox1.Image = Image.FromFile(pictureLocation);
    pictureBox1.Refresh();
}

我正在处理的项目有几个线程都访问相同的表单,这对我有用!

相关问题