Results 1 to 7 of 7

Thread: [RESOLVED] problem with running duplicate threads

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Feb 2008
    Location
    Botswana
    Posts
    107

    Resolved [RESOLVED] problem with running duplicate threads

    hey everyone. can anyone tell me how to call a function from a secondary thread. in my program, i have a background worker running. when the user clicks a button on the main form, i stop the background thread, run a function, but i cant get the background thread to start running again (i get an error saying the back ground worker is busy, which i dont get since i stopped the thread first. heres the code i got:

    Code:
        Private Sub BackgroundWorker1_DoWork( _
            ByVal sender As Object, _
            ByVal e As System.ComponentModel.DoWorkEventArgs) _
            Handles BackgroundWorker1.DoWork
    
      Do Until IsItCanceled = True
    
    
                Dim worker As System.ComponentModel.BackgroundWorker
                worker = CType(sender, System.ComponentModel.BackgroundWorker)
    
          Dim WC As Class2 = CType(e.Argument, Class2)
                WC.FindMyPort(worker, e)
    
            Loop
    
        End Sub
    Code:
        Private Sub BackgroundWorker1_ProgressChanged( _
            ByVal sender As Object, _
            ByVal e As System.ComponentModel.ProgressChangedEventArgs) _
            Handles BackgroundWorker1.ProgressChanged
    
            Dim state As Class2.CurrentState = _
                CType(e.UserState, Class2.CurrentState)
            Me.Label10.Text = "d"
    
        End Sub
    Code:
    Private Sub BackgroundWorker1_RunWorkerCompleted( _
        ByVal sender As Object, _
        ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) _
        Handles BackgroundWorker1.RunWorkerCompleted
    
            If e.Error IsNot Nothing Then
                MsgBox("Error: " & e.Error.Message)
                BackgroundWorker1.Dispose()
            ElseIf e.Cancelled Then
                MsgBox("Word counting canceled.")
                BackgroundWorker1.Dispose()
            Else
                     BackgroundWorker1.Dispose()
            End If
        End Sub
    class2:

    Code:
    Option Compare Text 
    
    Imports System.Windows.Forms
    Imports System.Data.OleDb
    Imports System
    Imports System.Data
    Imports System.Data.SqlClient
    Imports GsmComm.GsmCommunication
    Imports GsmComm.PduConverter
    Imports System.IO.Ports
    Imports System.IO.Ports.SerialPort
    Imports System.Text
    Imports System.IO
    
    
    Public Class Class2
        Public Class CurrentState
            Public LinesCounted As Integer
            Public WordsMatched As Integer
        End Class
        Public SourceFile As String
        Public CompareString As String
        Private WordCount As Integer = 0
        Private LinesCounted As Integer = 0
        Public isAmodem As Boolean = False
        Public Sub ShowMessage(ByRef MsgPDU As SmsDeliverPdu)
            Try
                Dim txtMsg As String = MsgPDU.UserDataText
                Dim FromNumber As String = MsgPDU.OriginatingAddress
                Dim FromAddress As String = MsgPDU.OriginatingAddress
                Dim TimeStamp As String = MsgPDU.GetTimestamp.ToString
                Dim MsgFromName As String = FindName(FromNumber)
    
                Dim AddString As String = "Insert into tblInboxMsg (MsgStatus,MsgFromNum,MsgFromName,TxtMsg,MsgTimeStamp) values" _
                & " ('New','" & FromAddress & "','" & MsgFromName & "','" & txtMsg & "','" & TimeStamp & "')"
                Debug.Print(AddString)
    
                '  Dim FileName As String = CurDir() & "\SMSer.mdb"
                Dim conn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\JasonWucinski.mdb;Persist Security Info=True;Jet OLEDB:Database Password=")
                Dim Cmd As OleDbCommand
                Dim objCmd As New OleDbCommand
                Cmd = New OleDbCommand(AddString, conn)
                conn.Open()
                objCmd = New OleDbCommand(AddString, conn)
                objCmd.ExecuteNonQuery()
                conn.Close()
                'JasonWucinskiBots5
                If Not (Cmd Is Nothing) Then Cmd.Dispose()
                Cmd = Nothing
                If Not (objCmd Is Nothing) Then objCmd.Dispose()
                objCmd = Nothing
            Catch ex As Exception
                Debug.Print("ex.ToString")
                Debug.Print(ex.ToString)
    
            End Try
        End Sub
    
        Public Sub FindMyPort(ByVal worker As System.ComponentModel.BackgroundWorker, _
            ByVal e As System.ComponentModel.DoWorkEventArgs)
    
            If worker.CancellationPending Then
                e.Cancel = True
                Exit Sub
            Else
        
                Dim getState As Boolean = False
                Dim getManu As String
                Dim storage = getMessageStorage()
                Dim MsgLocation As Integer
                Dim counter As Integer = 0
                Try
    
                    With comm
                        Try
                            .Open()
                 
                            Dim info As IdentificationInfo = comm.IdentifyDevice
                            getManu = info.Manufacturer
                            If getManu = "huawei" Then
                            
                                Try
                                
                                    Dim messages As DecodedShortMessage() = comm.ReadMessages(PhoneMessageStatus.ReceivedUnread, PhoneStorageType.Sim)
                        
                                    For Each DecodedShortMessage In messages
                             
                                        MsgLocation = DecodedShortMessage.Index
                              
                                        ShowMessage(DecodedShortMessage.Data)
                      
                                        counter = counter + 1
                                  Next
                                Catch ex As IOException
                                 
                                End Try
                                If counter >= 1 Then
                                    Try
                                      
                                     
                                        MsgBox("You got a new message")
    
                                    Catch ex As Exception
                                      
                                    End Try
    
                                End If
                                comm.Close()
                                Exit Try
                            End If
                        Catch Ex As IOException
                  
                        Catch Ex As Exception
                            
                        End Try
                    End With
                Catch ex As Exception
                   
                End Try
            End If
           
            Threading.Thread.Sleep(1000)
    
        End Sub
    
    
    End Class
    when the user click a button, i run this (after a bunch of other stuff)
    Code:
      Dim WC As New Class2
             IsItCanceled = False
            Me.BackgroundWorker1.RunWorkerAsync(WC)
    but all i get is an error saying the thread is bussy and cant have duplicates
    I am using Microsoft Visual Basic 2008 Express Edition. I use Access for my data base

  2. #2
    Frenzied Member MaximilianMayrhofer's Avatar
    Join Date
    Aug 2007
    Location
    IM IN YR LOOP
    Posts
    2,001

    Re: problem with running duplicate threads

    Don't loop a background worker, it's really not the way to handle this. Instead, why not have the FindMyPort method spawn itself unless it is flagged to stop? By using ThreadPool.QueueUserWorkItem() rather than simply calling the method directly each time, we can avoid memory leaks.

    vb.net Code:
    1. Public Class Class2
    2.     Public continue As Boolean = True
    3.  
    4.     Public Sub FindMyPort()
    5.         'Find your port
    6.  
    7.         If continue Then _
    8.             ThreadPool.QueueUserWorkItem(AddressOf FindMyPort)
    9.     End Sub
    10. End Class
    11.  
    12. Public Class Class1
    13.     Private WC As Class2
    14.    
    15.     Private Sub Class1_Load( _
    16.         ByVal sender As System.Object, _
    17.         ByVal e As System.EventArgs) Handles MyBase.Load
    18.        
    19.         WC = New Class2
    20.         ThreadPool.QueueUserWorkItem(AddressOf WC.FindMyPort)
    21.     End Sub
    22.  
    23.     Private Sub btnCancel_Click( _
    24.         ByVal sender As System.Object, _
    25.         ByVal e As System.EventArgs) Handles btnCancel.Click
    26.        
    27.         WC.continue = False
    28.     End Sub
    29. End Class
    Last edited by MaximilianMayrhofer; Sep 15th, 2008 at 09:59 PM.

  3. #3

    Thread Starter
    Lively Member
    Join Date
    Feb 2008
    Location
    Botswana
    Posts
    107

    Re: problem with running duplicate threads

    thanks for your reply. ive been trying to get your suggestion working. the only problem is that when i use this:

    Code:
    ThreadPool.QueueUserWorkItem(AddressOf WC.FindMyPort)
    if get a blue squiggly line uner WC.FindMyPort and the error is:
    Method 'Public sub FindMyPort(...)' does not have a signature compatible with delegate 'Delegate sub waitcallback(State as Object)'

    what does this mean? and how do i fix it?

    thanks
    jason
    I am using Microsoft Visual Basic 2008 Express Edition. I use Access for my data base

  4. #4
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: problem with running duplicate threads

    When you call QueueUserWorkItem you have to pass a WaitCallback delegate. A delegate is an object with a reference to a method. AddressOf is creating a reference to your FindMyPort method. The thing is, the method must have the same signature as the delegate, i.e. the same number, type and order of parameters and the same return type. As the error message is telling you, the WaitCallback delegate is a Sub, i.e. doesn't return anything, and has a single parameter of type Object. That means that your FindMyPort method must also be a Sub and must also have one parameter of type Object. There's no necessity to actually use the parameter value in the method but it's there so that you can pass data into the method like this:
    vb.net Code:
    1. ThreadPool.QueueUserWorkItem(AddressOf WC.FindMyPort, state)
    That second argument is the value that you get back from the parameter in the method.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  5. #5

    Thread Starter
    Lively Member
    Join Date
    Feb 2008
    Location
    Botswana
    Posts
    107

    Re: problem with running duplicate threads

    ok, to fix this (i think), i changed:
    Code:
        Public Sub FindMyPort(ByVal worker As System.ComponentModel.BackgroundWorker, _
            ByVal e As System.ComponentModel.DoWorkEventArgs)
    '...do stuff
    end sub
    to this:
    Code:
        Public Sub FindMyPort()
    '...do stuff
    end sub
    this seems to work. will removing the parameters cause problems later on?
    I am using Microsoft Visual Basic 2008 Express Edition. I use Access for my data base

  6. #6
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: problem with running duplicate threads

    Why were those parameters in there in the first place? because you needed to pass data from the BackgroundWorker's DoWork event handler. Given that you're not using a BackgroundWorker anymore...
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  7. #7

    Thread Starter
    Lively Member
    Join Date
    Feb 2008
    Location
    Botswana
    Posts
    107

    Re: problem with running duplicate threads

    good point
    thanks all
    untill my next thread question lol
    I am using Microsoft Visual Basic 2008 Express Edition. I use Access for my data base

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width