从VB.net中的另一个线程修改控件的属性 [英] Modifying the properties of controls from another thread in VB.net

查看:93
本文介绍了从VB.net中的另一个线程修改控件的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从另一个线程修改表单控件的属性,而无需创建单独的方法并为要修改的每个属性委托?

Is it possible to modify the properties of a forms controls from another thread without creating a separate method and delegate for each property that you want to modify?

我当前正在编写一个多线程应用程序,在这里我需要后台线程来操纵用户界面.与为单线程应用程序编写的代码相比,我觉得我编写的用于执行简单任务(例如设置控件的text属性)的代码量巨大.

I am currently writing a multithreaded application where I need background threads to manipulate the userinterface. I feel like the amount of code that I am writing to do simple tasks such as setting a control's text property is huge compared to the code I would write for a single threaded app.

在单线程应用程序中,您可以简单地使用Control.text ="My Text",但是到目前为止,在创建多线程应用程序时,我需要以下所有内容才能以线程安全的方式执行同一任务. /p>

In a single threaded app, one can simply use Control.text = "My Text", but so far when creating a multithreaded application, I need all of the following just to perform the same task in a thread safe way.

Delegate Sub ChangeTextDelegate(ByVal ctrl As Control, ByVal str As String)

Private Sub ChangeText(ByVal ctrl As Control, ByVal str As String)
    If ctrl.InvokeRequired Then
        ctrl.Invoke(New ChangeTextDelegate(AddressOf ChangeText), New Object() {ctrl, str})
        Return
    End If
    ctrl.Text = str
End Sub

对于许多简单的任务,我有很多类似的代码:

I have plenty of similar code that seems equally long for such simple tasks:

Delegate Sub ChangeVisibilityDelegate(ByVal ctrl As Control, ByVal bool As Boolean)

Private Sub ChangeVisibility(ByVal ctrl As Control, ByVal bool As Boolean)
    If ctrl.InvokeRequired Then
        ctrl.Invoke(New ChangeVisibilityDelegate(AddressOf ChangeVisibility), New Object() {ctrl, bool})
        Return
    End If
    ctrl.Visible = bool
End Sub

推荐答案

您正在使用委托和数组添加许多不必要的代码. addressof和{}语法都可以创建实例,因此您不需要构造函数或声明就可以:

You're adding a lot of unnecessary code with the delegate and the array. The addressof and {} syntax's both create instances so you don't need the constructors or declaration leaving you with:

Private Sub ChangeVisibility(ByVal ctrl As Control, ByVal bool As Boolean)
    If ctrl.InvokeRequired Then
        ctrl.Invoke(AddressOf ChangeVisibility, {ctrl, bool})
        Return
    End If
    ctrl.Visible = bool
End Sub

这是真正的主动清理,如果您的UI与逻辑分离,则开销很低.如果仍然存在问题,请查看是否可以通过单个方法重构多组ui更改来完成任务,而不是调用单个更改.然后可以完全保护这些方法.

This is real actively clean and if your UI is separate from your logic a low overhead. If this is still a problem look to see if you can refactor to groups of ui changes in a single method to accomplish a task rather than invoking a single change. These methods can then be cleanly protected.

这篇关于从VB.net中的另一个线程修改控件的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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