Solved

How do you fire events from a multithreaded class?

Posted on 2009-04-01
10
210 Views
Last Modified: 2012-05-06
I currently have a class that spawns different threads.  When certain things in those threads happen, I want it to fire off an event in the thread of the original "creator" of the class.  For instance, if the Form creates the object, all events should go to the Form's thread so it can make appropriate changes.

What I'm finding is that no matter what I do in the threads, I can NOT get the events to fire in the form without causing an error that the form's controls were created in a different thread.  Really need some help here, with a very clear explanation.
0
Comment
Question by:Javin007
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 5
10 Comments
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 24039904
What version VB.Net?....
0
 
LVL 4

Author Comment

by:Javin007
ID: 24041040
Express 2008.  
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 24045318
It sounds like you are manually creating threads and not using Invoke()/Delegates to properly marshal your calls across threads.  I can show you how to do that if you like...but with VB.Net 2005 (and above) it's often easier just to use the BackgroundWorker() Control as it does this automatically for you in the ProgessChanged() and RunWorkerCompleted() events:
http://msdn.microsoft.com/en-us/library/8xs8549b.aspx
http://msdn.microsoft.com/en-us/library/hybbz6ke.aspx
0
Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

 
LVL 4

Author Comment

by:Javin007
ID: 24050134
I did attempt to use Invoke/Delegates, but continued to get the same error when calling the delegated method, so obviously have that set up wrong.

The BackgroundWorker seems like a better option *IF* it can "talk" back to the calling class so that class can raise events.  From what I've read here, it seems like they expect the method to just run, and eventually stop.  This loop that will be threaded should run the entire time the app is running, and occasionally fire events.  (Long story short, I'm attempting to make a sockets wrapper class.)
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 24050309
You can place an Infinite loop inside the "worker" method of the BackgroundWorker control.  The thread will be automatically killed when the app is closed.

The ReportProgress() method will cause the ProgressChanged() Event to fire:
http://msdn.microsoft.com/en-us/library/a3zbdb1t.aspx
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 24050314
Do you need to see a simple example?...
0
 
LVL 4

Author Comment

by:Javin007
ID: 24050359
A small example would be awesome, thanks!
0
 
LVL 4

Author Comment

by:Javin007
ID: 24050508
Also keep in mind that this is a class, so not a form.  I'll need to create a BackgroundWorker object in code for it to be contained in the class.
0
 
LVL 86

Accepted Solution

by:
Mike Tomlinson earned 500 total points
ID: 24052401
Okey dokey...here is a class that encapsulates a BackgroundWorker and raises a custom event.  Note that we do NOT have to do any manual marshalling with Invoke()/Delegates:
Public Class Form1
 
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim mo As New MyOperation
        AddHandler mo.SomethingHasHappened, AddressOf MyOperation_SomethingHasHappened
    End Sub
 
    Private Sub MyOperation_SomethingHasHappened(ByVal msg As String, ByVal stamp As DateTime)
        Label1.Text = msg & " | " & stamp.ToString
    End Sub
 
End Class
 
Public Class MyOperation
 
    Public Event SomethingHasHappened(ByVal msg As String, ByVal stamp As DateTime)
 
    ' obviously you can have more of these things in your class...
    Private WithEvents bgw As New System.ComponentModel.BackgroundWorker
 
    Private counter As Integer
 
    Public Sub New()
        bgw.WorkerReportsProgress = True
        bgw.WorkerSupportsCancellation = True
        bgw.RunWorkerAsync()
    End Sub
 
    Private Sub bgw_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bgw.DoWork
        ' backgroundworkers get killed automatically when the app shuts down...
        While True
            ' you can acess anything inside MyOperation from here to make decisions etc...
            System.Threading.Thread.Sleep(1000)
            counter = counter + 1
            bgw.ReportProgress(counter) ' this just makes ProgressChanged() fire below
        End While
    End Sub
 
    Private Sub bgw_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles bgw.ProgressChanged
        ' this is already marshaled to the UI thread because the MyOperation class was created on the UI thread
        ' make the main UI receive the event
        ' again, you can acess stuff inside MyOperation if need be, or pass things via "e.UserState" from the "worker"
        RaiseEvent SomethingHasHappened("Greeting #" & e.ProgressPercentage, DateTime.Now)
    End Sub
 
    Private Sub bgw_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bgw.RunWorkerCompleted
        ' you can raise a different event here...
    End Sub
 
End Class

Open in new window

0
 
LVL 4

Author Closing Comment

by:Javin007
ID: 31565228
Perfect!  This is exactly what I needed.  Delegates/Invoke was entirely too complex.
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Enums (shorthand for ‘enumerations’) are not often used by programmers but they can be quite valuable when they are.  What are they? An Enum is just a type of variable like a string or an Integer, but in this case one that you create that contains…
Background What I'm presenting in this article is the result of 2 conditions in my work area: We have a SQL Server production environment but no development or test environment; andWe have an MS Access front end using tables in SQL Server but we a…
Show developers how to use a criteria form to limit the data that appears on an Access report. It is a common requirement that users can specify the criteria for a report at runtime. The easiest way to accomplish this is using a criteria form that a…
This lesson covers basic error handling code in Microsoft Excel using VBA. This is the first lesson in a 3-part series that uses code to loop through an Excel spreadsheet in VBA and then fix errors, taking advantage of error handling code. This l…

696 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question