Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
c#:螺纹不工作_C#_Multithreading - Fatal编程技术网

c#:螺纹不工作

c#:螺纹不工作,c#,multithreading,C#,Multithreading,我希望在转换器处理时显示GIF图像。但GIF图像从未显示,并且转换过程在大约20秒的时间内成功完成,因此图片框为空白。 如果我用MessageBox.Show替换转换器进程,Gif图像和Message.Show都可以正常工作 我需要做什么 Thread th = new Thread((ThreadStart)delegate { pictureBox1.Image = Image.FromFile("loading_gangnam.gif");

我希望在转换器处理时显示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);

您正在从与主UI线程不同的线程访问表单控件。 您需要使用Invoke()


有关示例,请参见,UI的绘制是在绘制事件期间完成的,只有在代码完成任何思考后,才会处理该事件

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

选项:

  • 处理部分图像,然后让其绘制,并安排计时器或其他事件以立即继续绘制
  • 隔离的(非UI)图像上的背景线程上执行工作,定期复制当前工作图像的副本,并使用
    pictureBox1。调用(…)
    副本设置为图片框的内容

还有一种明确的方式可以让事件在UI循环中进行处理,但这确实是一种糟糕的做法,我甚至不能直接提到它的名字。

你已经把线程向后推了。您希望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/ms171728.aspx

尝试使用此功能设置加载的\u 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();
}
public void newPicture(字符串pictureLocation)
{
如果(需要调用)
{
调用(新操作(newPicture),新对象[]{pictureLocation});
}
pictureBox1.Image=Image.FromFile(pictureLocation);
pictureBox1.Refresh();
}

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

不要直接从线程访问UI元素。看看backgroundworker或invoke。我也会把长时间运行的精简放在一个线程中。这是非常正确的,但不是OP看到的特定问题的主要原因(编辑时UI没有更新)。不过绝对值得一提。但我不确定它是否真的回答了这个问题。@MamaduBascoBah-没问题。如果被标记为答案,我将不胜感激。