如何在backgroundworker中更改textbox.text? [英] How to change textbox.text while in backgroundworker?

查看:111
本文介绍了如何在backgroundworker中更改textbox.text?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想在后台工作人员中更改文本框文本. 我所拥有的是:

I just want to change an textbox text while I am in the backgroundworker. What I have is:

Private Sub ...

 Dim powershellWorker As New BackgroundWorker
        AddHandler powershellWorker.DoWork, AddressOf BackgroundWorker1_DoWork

        powershellWorker.RunWorkerAsync()

End Sub

Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork

 If stuff <> "lol" Then
            test.Text = stuff

End Sub

它给我一个错误:无效的线程-边界操作"(谷歌翻译)

It gives me the error: "Invalid thread -border operation" (google translated)

推荐答案

您不能从创建控件的线程之外的线程更改大多数控件属性.

You can't change most control properties from a thread other than the thread in which the control was created.

检查是否需要调用,即当前代码正在创建控件(TextBox测试)的线程之外的线程上执行.如果test.InvokeRequired为true,则应调用该呼叫.

Check if invoke is required, i.e. the current code is executing on a thread other than the thread in which the control (TextBox test) was created. If test.InvokeRequired is true, then you should Invoke the call.

Private Sub ...
    Dim powershellWorker As New BackgroundWorker
    AddHandler powershellWorker.DoWork, AddressOf BackgroundWorker1_DoWork

    powershellWorker.RunWorkerAsync()

End Sub

Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork

    If stuff <> "lol" Then
        If test.InvokeRequired Then  
            test.Invoke(Sub() test.Text = stuff)
        Else
            test.Text = stuff
        End If
    End If
End Sub

您可以使用此扩展方法自动执行调用所需的模式:

You can automate the invoke required pattern with this extension method:

<Extension()>
Public Sub InvokeIfRequired(ByVal control As Control, action As MethodInvoker)
    If control.InvokeRequired Then
        control.Invoke(action)
    Else
        action()
    End If
End Sub

然后您的代码可以简化为:

Then your code could be simplified to:

Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork

    If stuff <> "lol" Then
        test.InvokeIfRequired(Sub() test.Text = stuff)
    End If
End Sub

这篇关于如何在backgroundworker中更改textbox.text?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆