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# BackgroundWorker使用秒表更新运行时间标签,由于调用C而冻结#_C#_Multithreading_Backgroundworker_Background Process_Invoke - Fatal编程技术网

C# BackgroundWorker使用秒表更新运行时间标签,由于调用C而冻结#

C# BackgroundWorker使用秒表更新运行时间标签,由于调用C而冻结#,c#,multithreading,backgroundworker,background-process,invoke,C#,Multithreading,Backgroundworker,Background Process,Invoke,我正在尝试创建一个实时秒表,它在用户控件内的后台工作程序中运行,并且我正在使用Invoke方法更新标签,该标签是UI中经过的时间。当两个后台工作程序同时运行时,它工作正常 我注意到问题是,我试图每秒调用一次标签,然后乘以我创建的用户控件的数量,因此它会冻结。我试图对调用方法进行注释。它只是工作正常,但如果没有调用方法,我无法用经过的时间更新标签 public void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) {

我正在尝试创建一个实时秒表,它在用户控件内的后台工作程序中运行,并且我正在使用Invoke方法更新标签,该标签是UI中经过的时间。当两个后台工作程序同时运行时,它工作正常

我注意到问题是,我试图每秒调用一次标签,然后乘以我创建的用户控件的数量,因此它会冻结。我试图对调用方法进行注释。它只是工作正常,但如果没有调用方法,我无法用经过的时间更新标签

public void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
     Stopwatch stopWatch = new Stopwatch();
     stopWatch.Start();
     while (!backgroundWorker1.CancellationPending)
     {
         TimeSpan ts = stopWatch.Elapsed;
         string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}", ts.Hours,ts.Minutes, ts.Seconds);               
         label2.Invoke((MethodInvoker)delegate
         {
             label2.Text = elapsedTime;
         });
     }
     stopWatch.Stop();
}
这是使用秒表生成的用户控件的图像


考虑到可能有多个用户控件同时运行,我如何用经过的时间更新标签而不使应用程序冻结。

我认为我应该使用计时器,而不是后台工作程序,它可以用于此类问题

Stopwatch sw = new Stopwatch();

private void timer1_Tick(object sender, EventArgs e)
{
    long h = sw.Elapsed.Hours;
    long m = sw.Elapsed.Minutes;
    long s = sw.Elapsed.Seconds;
    long t = sw.Elapsed.Ticks;

    string strH = (h < 10) ? "0" + h : h + "";
    string strM = (m < 10) ? "0" + m : m + "";
    string strS = (s < 10) ? "0" + s : s + "";
    string AllTime = strH + ":" + strM +":"+ strS;

    label2.Text = AllTime;
}```
Stopwatch sw=新秒表();
私有无效计时器1_刻度(对象发送方,事件参数e)
{
长h=短程运行小时数;
长m=短波经过的分钟数;
长s=sw.persed.Seconds;
长t=sw.eassed.Ticks;
字符串strH=(h<10)?“0”+h:h+”;
字符串strM=(m<10)?“0”+m:m+”;
字符串strS=(s<10)?“0”+s:s+”;
字符串AllTime=strH+“:”+strM+“:”+strS;
label2.Text=所有时间;
}```

调用
在这里真的不值得责备-尝试不断更新表单上的元素将冻结表单,无论您如何操作。@AlexeiLevenkov我注意到这不是最好的方法that@AlexeiLevenkov所以没有什么好办法可以在表格中制作一个实时秒表?