0

I have a Winform GUI that have an UDPClient listener thread working on second plane to avoid halt the GUI; when the thread receive something call a Sub in the WinForm code; that Sub process the data and must to fill different TextBox depending on the received data.

As you know if I try to change the text property of any control from the Sub I will receive a Cross Thread error. So in order to avoid that I make some delegates for a few control(just a test) and works OK.

But the WinForm have more than 100 controls and I was wondering if there's some way to do it with less code.

Making a search I found this two questions.

Multi-threaded WPF Application: Dispatcher Invoke. A more efficient way?

Change WPF controls from a non-main thread using Dispatcher.Invoke

On the first link they talk about use Dispacher, something like

Public Shared Sub UiInvoke(a As Action)
    Application.Current.Dispatcher.Invoke(a)
End Sub

I wrote that code in my Form but the IDE(VS2010/NET4.0) says that "Current" is not a member.

I think I'm missing something, I never used before or do something similar as Dispacher, I usually use Delegates.

What I'm doing wrong? There's another way to control many controls with one Delegate? I just need to read or write the text property.

Community
  • 1
  • 1
E_Blue
  • 1,021
  • 1
  • 20
  • 45
  • Start buy not using application.current - there may be more than one dispatcher. get the dispather on the window. – TomTom May 13 '14 at 15:44
  • Are you talking about do something like? 'code' Public Shared Sub UiInvoke(ByVal a As Action) Dispatcher.Invoke(a) End Sub 'code' – E_Blue May 13 '14 at 15:46
  • Yes. One day you may find code that has multiple UI Threads, each running one or more windows. THis is easily doable, but it makes the concept of a "current" dispatcher on application level a little totally moot. – TomTom May 13 '14 at 15:47
  • Are you using winforms OR WPF? your question is completely unclear. WPF solutions won't work in winforms, and BTW you'd rather not use winforma at all. – Federico Berasategui May 13 '14 at 16:18
  • @HighCore - I'm using WinForm, I thought it was the same just called different. – E_Blue May 13 '14 at 17:20

1 Answers1

1

You can use anonymous Subs:

Me.Invoke(
    Sub()
        ' Update controls here
    End Sub)
Ry-
  • 218,210
  • 55
  • 464
  • 476
  • I wrote the following inside a Private Sub Me.Invoke(Sub(),Me.UtcDateTxt.Text="140505") and the VS IDE says " Lambda expressions of a single line statement must contain exactly one instruction"; underline on Sub(). – E_Blue May 13 '14 at 18:43
  • @E_Blue, I don’t know where you got the comma from. Use exactly as shown. – Ry- May 14 '14 at 03:01
  • Sorry, my bad, I read the single quote(') as coma; now is working, thanks. – E_Blue May 14 '14 at 12:31