C# 如何将BackgroundWorker与主线程函数一起使用?
好的,我尽量不说得太具体,但是,下面是:C# 如何将BackgroundWorker与主线程函数一起使用?,c#,C#,好的,我尽量不说得太具体,但是,下面是: public void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { DateTime startTeste = DateTime.Now; DateTime finishTeste = startTeste.AddSeconds(mTeste + sTeste); while(DateTime.Now <
public void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
DateTime startTeste = DateTime.Now;
DateTime finishTeste = startTeste.AddSeconds(mTeste + sTeste);
while(DateTime.Now <= finishTeste) //enquanto o teste nao terminar
{
if(backgroundWorker1.CancellationPending)
{
e.Cancel = true;
break;
}
backgroundWorker1.ReportProgress((int)(DateTime.Now - startTeste).TotalSeconds + 30);
//AtualizarVal();
Teste();
System.Threading.Thread.Sleep(30000);
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
tProgress.Value = e.ProgressPercentage; //atualiza as barras de progresso
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if(e.Cancelled) //Caso seja cancelado o BGW
{
MessageBox.Show("Thread got canceled");
}
if(nTeste == nTestes)
{
buttonSTART.Enabled = true;
timer1.Stop();
MessageBox.Show("Job done");
}
}
我唯一想做的就是,每30秒写入一个文本框,我必须在一个线程中写入,因为我要写入更多的文本框,我要通过RS-232发送控件,因为这些控件和一个定时器我需要使用线程,这样,当我的程序通过RS-232发送和接收数据时,我的计时器就不会出错
也许这是太多的代码,但我想这样我会让你明白发生了什么。你不能从其他线程访问UI组件文本框、消息框等
public void BackgroundWorker1DoWork(object sender, DoWorkEventArgs e)
{
//After some Work Done
Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new
ThreadStart(delegate
{
Teste();
}));
}
您想继续使用Backgroundworker还是愿意使用async/await/Task?您知道BGW的功能吗?我们需要更多信息。您是否无权访问tbtatual文本框,或者是否存在其他错误?在DoWork函数中,您无法访问任何UI元素。您必须使用RunWorkerCompleted。我还是建议使用async/await,因为它通常更灵活、更现代。@Joelius You不能显得有点太严格。实际上,您可以通过执行一些严重的扭曲规则(如跨线程编组调用)来实现。但我认为我们同意,不应该这样做。@Fildor好吧,也许我应该指定。您绝对不应该使用后台线程来更新UI。我甚至会说,除了报告进度之外,这几乎与后台线程的用途相反。你不能从其他线程访问UI组件文本框、消息框等是正确的,但我认为你发布的代码不是一个好的解决方案。这不仅很难理解,而且很糟糕,因为看起来您在这里所做的事情正是RunWorkerCompleted事件的目的。这将在您有权访问UI元素的主线程上再次调用。@Joelius对于中间UI交互,还有ReportProgress,但我不知道它是否符合OP的要求。它只是为了这个目的——向用户界面报告一些进展。如更新ProgressBar等。如果BackgroundWorker是从UI线程创建的,则RunWorkerCompleted事件也将在UI线程上引发。如果它是从后台线程创建的,事件将在未定义的后台线程上引发。如果在此上下文中您不知道谁在创建后台线程thread@phantasm如果您从其他BGW启动BGW,您会遇到比更新UI中的字段更大的问题…:D@phantasm我很想去,但不幸的是,我仍然不确定OP到底想要什么。似乎他们正试图从后台工作人员那里更新UI。我不知道你为什么要做这样的事,我决不会向初学者提议这样做。也许他们需要的是aync/等待,或者他们想要进度报告。我们甚至还没有看到DoWork方法的其他部分,或者没有其他部分?。。他们说我的主要问题不是这样做。。那又是什么呢?
public void BackgroundWorker1DoWork(object sender, DoWorkEventArgs e)
{
//After some Work Done
Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new
ThreadStart(delegate
{
Teste();
}));
}