Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/283.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.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#Windows窗体,I';我正在尝试更新线程中的标签_C#_Multithreading_Winforms_Asynchronous - Fatal编程技术网

C#Windows窗体,I';我正在尝试更新线程中的标签

C#Windows窗体,I';我正在尝试更新线程中的标签,c#,multithreading,winforms,asynchronous,C#,Multithreading,Winforms,Asynchronous,我正在尝试更新线程中的标签。我尝试了多种不同的方法,但仍然无法更新我的标签。这里是我的代码 public form1() { InitializeComponent(); new Thread(SampleFunction).Start(); } private void setLabel1TextSafe(string txt) { if (label1.InvokeRequired) { label1.Invoke(new Action(()

我正在尝试更新线程中的标签。我尝试了多种不同的方法,但仍然无法更新我的标签。这里是我的代码

public form1()
{
    InitializeComponent();
    new Thread(SampleFunction).Start();
}
private void setLabel1TextSafe(string txt)
{
    if (label1.InvokeRequired)
    {
        label1.Invoke(new Action(() => label1.Text = txt));
        return;
    }
    label1.Text = txt;
}
public void AppendText(string value)
{
    label1.Text += value;
}
void SampleFunction()
{
    // Gets executed on a seperate thread and 
    // doesn't block the UI while sleeping
    for (int i = 0; i < 5; i++)
    {
        setLabel1TextSafe("Heya");
        Thread.Sleep(1000);
    }
}
public form1()
{
初始化组件();
新线程(SampleFunction.Start();
}
私有void setLabel1TextSafe(字符串txt)
{
if(标签1.InvokeRequired)
{
label1.Invoke(新操作(()=>label1.Text=txt));
返回;
}
label1.Text=txt;
}
公共文本(字符串值)
{
标签1.文本+=值;
}
void SampleFunction()
{
//在单独的线程上执行,并且
//睡眠时不会阻塞UI
对于(int i=0;i<5;i++)
{
setLabel1TextSafe(“Heya”);
睡眠(1000);
}
}

转换时没有错误,但标签文本没有更改或更新。有人可以帮助吗?谢谢你

谢谢你的编辑我对代码块有问题@reza aghaeiYou're welcome:)你的代码似乎正常工作。您的表单中是否还有其他线程或
Thread.Sleep()
其他地方?如果您总是发送相同的值“Heya”,那么ir为什么应该更改?尝试发送另一个值,看看它是否更改heya只是一个测试变量,它应该在线程@Sameh中从“Label1”更改为“heya”