473,480 Members | 3,106 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

VB .NET cross-threading challenge

5 New Member
I'm using a 3rd party .NET library which monitors a peripheral with a backgroundworker. I've added a handler to catch a raised event, but when I try to update the UI I receive an exception because my UI call is on the raised event thread from the background worker and not the UI thread. The 3rd party library states that UI events should be called with ControlBeginInvoke, but I've had no luck trying to get it to work. The program is supposed to be very simply; so, I'd like to avoid a lot of plumbing if possible. Here's what I have so far. I'm not including all of my attempts to call the UI thread.
Expand|Select|Wrap|Line Numbers
  1. Public Class frmMain
  2.     Dim m_ctmPeripheralManager As PeripheralDeviceManager = PeripheralDeviceManager.Singleton
  3.  
  4.     Private Sub fmrMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  5.     ' Start the peripheral Manager
  6.         m_ctmPeripheralManager.Startup(True)
  7.     ' Attach the event handlers
  8.         AddHandler m_ctmPeripheralManager.PeripheralActivatedEvent, AddressOf testEvent
  9.         AddHandler m_ctmPeripheralManager.PeripheralDeActivatedEvent, AddressOf testEvent2
  10.     End Sub
  11.  
  12.  
  13.     Private Sub testEvent(ByVal sender As Object, ByVal args As PeripheralDeviceEventArgs)
  14.         ' Update the UI TextBox == This fails b/c the UI thread doesn't call this function
  15.     txtOutput.Text = txtOutput.Text & vbCrLf & ("Got " & args.PeripheralDevice.InternalName & ", on slot " & args.Slot.ToString)
  16.     End Sub
  17.  
  18.     Private Sub testEvent2(ByVal sender As Object, ByVal args As PeripheralDeviceEventArgs)
  19.     ' Update the UI TextBox == This fails b/c the UI thread doesn't call this function
  20.         txtOutput.Text = txtOutput.Text & vbCrLf & ("Got " & args.PeripheralDevice.InternalName & ", on slot " & args.Slot.ToString)
  21.     End Sub
  22.  
  23. End Class
TIA.
Oct 21 '07 #1
12 7208
Shashi Sadasivan
1,435 Recognized Expert Top Contributor
I had a similar issue sometime ago.
and my non main thread was chaging the UI

I used the control.InvokeRequired for this
I basically chnaged the UI is this was true.

It worked for me. But for some reason i think i took the threading off my application.

good luck
Oct 22 '07 #2
thanksinadvance
5 New Member
I had a similar issue sometime ago.
and my non main thread was chaging the UI

I used the control.InvokeRequired for this
I basically chnaged the UI is this was true.

It worked for me. But for some reason i think i took the threading off my application.

good luck
Hmmm... InvokeRequired confirms that an Invoke is required. So, in my initial post I stated that I need to call Invoke or BeginInvoke, but I can't seem to get it to work properly. The code initially posted is mine, and it calls the 3rd party .NET library. This library has a (static) singleton which, when set to true, initializes a backgroundworker thread in the 3rd party library. I have no direct control over the "Black Box," and so I really have no clear alternative other than to figure out how to get the cross-thread function call to work in response to an event raised from the "Black Box." I can't remove threading from the app.
Oct 22 '07 #3
Shashi Sadasivan
1,435 Recognized Expert Top Contributor
If your 3rd party code is controlling the properties of the controls (UI based) and you cannot to anything to that, then i think you should ask them for support for this issue!
Oct 22 '07 #4
thanksinadvance
5 New Member
The 3rd party library just raises events and provides interfaces to the peripherals. I write the UI. The problem is that when the 3rd party library raises an event (like a device being activated) by using its background worker, I wind up handling that event by calling testEvent (or testEvent2). These are sub's that I wrote, but which are executing under the 3rd party library's background worker thread (which raised the event). Therefore, when I try to manipulate the UI, I get a cross-thread error. I've not been successful in trying to use Invoke or BeginInvoke to make an asynchronous call back to the UI thread (i.e., the code I've written). The help I need is in getting the cross-thread sub call to work.
Oct 22 '07 #5
Shashi Sadasivan
1,435 Recognized Expert Top Contributor
Allright,
that then brings it back to my first post.
Check if the control needs to be invoked.
if the controls invoke required is true then the control was instantiated on a different thread.
So only on a false should you be changing its properties.
check the msdn library
Oct 22 '07 #6
thanksinadvance
5 New Member
Allright,
that then brings it back to my first post.
Check if the control needs to be invoked.
if the controls invoke required is true then the control was instantiated on a different thread.
So only on a false should you be changing its properties.
check the msdn library
The txtOutput.InvokeRequire returns true as the code is currently written. That is the problem I'm trying to overcome. The txtOutput object (a textbox in the UI) was created by me on a form (let's say it is running on thread 10). I need to update its Text property with the date returned from the background worker (3rd party lib) which is operating on a separate thread (let's say it is running on thread 11). So, how do I get to a situation where the invokerequired is false? That is, how do I call from the background worker thread (#11) a change on an object in my UI thread( #10)? I know that I need to use invoke or begininvoke, and I must have tried at least 10 or 15 different says to use invoke or begininvoke, and none that I've tried successfully changes the txtOutput.Text property because I can't break out of the background worker thread to update the UI. Even when I've used Invoke, it still seems to run against the background worker thread, and so, I continually get a runtime error about cross-thread functions calls. Do I call invoke on the txtOutput object? frmMain object? What parameters does it need? I've read multiple MSDN articles and none of them have been of help, which is my reason for posting here. I'd not have posted if I hadn't researched aggressively. There's simply a concept that I'm missing which is key to unlocking this challenge.
Oct 22 '07 #7
thanksinadvance
5 New Member
OK... So, I'm now back in the main thread... Here's what I added
Expand|Select|Wrap|Line Numbers
  1. Delegate Sub InvokeDelegate()
and in the testEvent I added a call to another function
Expand|Select|Wrap|Line Numbers
  1. txtOutput.BeginInvoke(new InvokeDelegate(AddressOf updateText))
Now I just need to figure out how to pass the parameters I have to the updateText function.
Oct 22 '07 #8
Shashi Sadasivan
1,435 Recognized Expert Top Contributor
Dont complicate it so much
Try this first before you jump into delegates!
Expand|Select|Wrap|Line Numbers
  1. if(InvokeRequired == true)
  2. {
  3.  
  4. }
  5. else
  6. {
  7. //update UI here
  8. }
Oct 22 '07 #9
PongaPundit
1 New Member
OK... So, I'm now back in the main thread... Here's what I added
Expand|Select|Wrap|Line Numbers
  1. Delegate Sub InvokeDelegate()
and in the testEvent I added a call to another function
Expand|Select|Wrap|Line Numbers
  1. txtOutput.BeginInvoke(new InvokeDelegate(AddressOf updateText))
Now I just need to figure out how to pass the parameters I have to the updateText function.
Hi,
Invoke() as I understand (with my Win32 API programming background) posts message to the message queue associated with a window (i.e. a form).
So instead of invoking on txtOutput, try the form object:
Expand|Select|Wrap|Line Numbers
  1. frmObject.BeginInvoke(new InvokeDelegate(AddressOf updateText))
Replace frmObject above with your actual form object. It should work fine.
Oct 29 '07 #10
balabaster
797 Recognized Expert Contributor
In vb it would be done in the following way (assuming you are running an update on objects from within your form - i.e. this sub/delegate pair would both be in the codebehind for this form):

Expand|Select|Wrap|Line Numbers
  1.  
  2. Class MyForm
  3.  
  4.   Private Delegate Sub SetTextDelegate(ByVal InputStr As String)
  5.  
  6.   Private Sub SetText(ByVal InputStr As String)
  7.     If Me.InvokeRequired Then
  8.       Me.Invoke(New SetTextDelegate(AddressOf SetText), InputStr)
  9.     Else
  10.       Me.TextBox1.Text = InputStr
  11.     End If
  12.   End Sub
  13.  
  14.   Private Sub Clicked(ByVal Sender As Object, ByVal e As System.EventArgs) _
  15.   Handles MyButton1.Click
  16.     SetText("Hello World")
  17.   End Sub
  18.  
  19. End Class
  20.  
  21.  
A slightly more complex example would be invoking this from another thread. The code is a little hokey, but it demonstrates the point (as well as demonstrates how to pass data into a thread at instantiation).

Expand|Select|Wrap|Line Numbers
  1. Public Class MyForm
  2.  
  3.     Private Delegate Sub SetTextDelegate(ByVal InputStr As String)
  4.  
  5.     Private Sub SetText(ByVal InputStr As String)
  6.         If Me.InvokeRequired Then
  7.             Me.Invoke(New SetTextDelegate(AddressOf SetText), InputStr)
  8.         Else
  9.             Me.TextBox1.Text = InputStr
  10.         End If
  11.     End Sub
  12.  
  13.     Private Sub MyWorkerThread(ByVal Sender As Object)
  14.         SetText(CType(Sender, String))
  15.     End Sub
  16.  
  17.     Private Sub Loaded(ByVal sender As Object, ByVal e As System.EventArgs) _
  18.     Handles Me.Load
  19.         Dim oThread As New System.Threading.Thread(AddressOf MyWorkerThread)
  20.         oThread.Start("Hello World")
  21.     End Sub
  22.  
  23. End Class
  24.  
In this manner it doesn't matter whether you call this routine from within your form directly or from another thread instantiated by the form. If you want to set the text property of your control you can invoke it using the same call:

Expand|Select|Wrap|Line Numbers
  1. SetText("Hello World")
Oct 30 '07 #11
balabaster
797 Recognized Expert Contributor
Um...just realised I didn't apply my example to your scenario...in your scenario, you would put the code to modify your 3rd party component in the Else statement in your "SetText" routine - I put "SetText" in quotes because obviously in your specific example it wouldn't be named that as the subroutine is being used for something quite different. I just used that as an abstract example to demonstrate the concept.
Oct 30 '07 #12
Plater
7,872 Recognized Expert Expert
The Exception message details includes some statements that tell you exactly what to look up in msdn to find a way around this.
I cannot find it now since I don't have the Exception, but here is the example they provide:

Expand|Select|Wrap|Line Numbers
  1. private void SetText(string text)
  2. {
  3.    // InvokeRequired required compares the thread ID of the
  4.    // calling thread to the thread ID of the creating thread.
  5.    // If these threads are different, it returns true.
  6.    if (this.myTextBox.InvokeRequired)
  7.    {
  8.       SetTextCallback d = new SetTextCallback(SetText);
  9.       this.Invoke(d, new object[] { text });
  10.    }
  11.    else
  12.    {
  13.       this.myTextBox.AppendText(DateTime.Now.ToString()+": "+ text);
  14.    }
  15. }
  16.  
Oct 30 '07 #13

Sign in to post your reply or Sign up for a free account.

Similar topics

0
2030
by: Web Science | last post by:
Site and Features: http://www.eigensearch.com Search engine, eigenMethod, eigenvector, mathematical, manifolds, science, technical, search tools, eigenmath, Jacobian, quantum, mechanics,...
12
3841
by: * ProteanThread * | last post by:
but depends upon the clique: ...
3
3068
by: rollasoc | last post by:
Hi, Doing a bit of system testing on a Windows 98 laptop. (.Net 1.1 app). Did a bit of testing. Loaded a previously saved file. A gray box appeared with the text and buttons all white...
0
1858
by: Web Science | last post by:
Site and Features: http://www.eigensearch.com Search engine, eigenMethod, eigenvector, mathematical, manifolds, science, technical, search tools, eigenmath, Jacobian, quantum, mechanics,...
23
6477
by: Jeff Rodriguez | last post by:
Here's what I want do: Have a main daemon which starts up several threads in a Boss-Queue structure. From those threads, I want them all to sit and watch a queue. Once an entry goes into the...
0
2034
by: Web Science | last post by:
Site and Features: http://www.eigensearch.com Search engine, eigenMethod, eigenvector, mathematical, manifolds, science, technical, search tools, eigenmath, Jacobian, quantum, mechanics,...
1
2742
by: Rob Woodworth | last post by:
Hi, I'm having serious problems getting my report to work. I need to generate a timesheet report which will contain info for one employee between certain dates (one week's worth of dates). I...
6
8590
by: Simon | last post by:
Hi All, An experiment i'm doing requires requires a synchronous cross-domain request, without using a proxy. I wondered if anyone had any ideas to help me achieve this. Below is what I have...
6
5454
by: Bart Van der Donck | last post by:
Hello, I'm presenting my new library 'AJAX Cross Domain' - a javascript extension that allows to perform cross-domain AJAX requests. http://www.ajax-cross-domain.com/ Any comments or...
6
3963
by: ampo | last post by:
Hello. Can anyone help with cross-domain problem? I have HTML page from server1 that send xmlHTTPRequest to server2. How can I do it? Thanks.
0
6920
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
1
6763
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7030
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5367
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
4799
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
3015
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3011
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
574
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
210
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.