Solved

vb.net background worker doesn't seem to be working

Posted on 2010-09-01
10
581 Views
Last Modified: 2012-05-10
I copied my code from another program I wrote that works perfectly. I must be missing some small detail and I can't find it. Can someone please tell me why my BGW isn't picking up the copy or move to folder?

Thanks.
Option Strict Off
Imports System.IO
Imports System.Collections.Generic
Public Class Form1
    Inherits System.Windows.Forms.Form
    Public Function ExecCommand(ByRef CommandLine As String, _
                        Optional ByRef Arguments As String = "", _
                        Optional ByRef Waitforexit As Boolean = True) As Integer
        Dim psi As New ProcessStartInfo()
        Dim p As Process

        With psi
            .FileName = CommandLine
            .Arguments = Arguments
            .WindowStyle = ProcessWindowStyle.Hidden 'This avoid a text window being opened
        End With
        Try
            p = Process.Start(psi) 'This line runs the command
            If Waitforexit Then p.WaitForExit() 'This wait until the command ends

            While Not p.HasExited
                System.Windows.Forms.Application.DoEvents()
            End While

            Return p.ExitCode
        Catch e As System.Exception
            'Catch errors here
        End Try
    End Function
    Private Sub bgw_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bgw.DoWork
        Dim FileName As String
        Dim HasMoreItems As Boolean

        While True
            Files.MRE.Reset()
            HasMoreItems = False
            Do
                FileName = Nothing
                SyncLock Files.SharedObject
                    If Files.ToBeProcessed.Count > 0 Then
                        FileName = Files.ToBeProcessed.Peek
                    End If
                End SyncLock
                If Not IsNothing(FileName) Then
                    While IsFileInUse(FileName)
                        Debug.Print(DateTime.Now.ToString() & " : File in use!  Waiting 5 seconds...")
                        System.Threading.Thread.Sleep(5000) ' wait 5 seconds to try again
                    End While


                    Try

                        If FileName.Contains("15Mbps") Then System.IO.File.Copy("C:\video\" & FileName, "X:\encoded2\mcvod\transcode_needed" & FileName, True) Else 
                        System.IO.File.Copy("C:\video\" & FileName, "Z:\" & FileName, True)
                        System.IO.File.Copy("C:\video\" & FileName, "X:\Encoded2\" & FileName, True)
                        If FileName.Contains("HD") Then HDList.Items.Add(FileName)
                        If FileName.Contains("FVOD") Then FVODList.Items.Add(FileName)
                        If FileName.Contains("15Mbps") Then IPVODList.Items.Add(FileName)
                        If FileName.Contains("HD") Or ("FVOD") Or ("15Mbps") Then BadLabel.ForeColor = Color.Green Else BadList.Items.Add(FileName)

                        System.IO.File.Delete("c:\video\" & FileName)
                        SyncLock Files.SharedObject
                            Files.ToBeProcessed.Dequeue()
                        End SyncLock
                        bgw.ReportProgress(0, FileName)
                    Catch ex As Exception
                        System.Threading.Thread.Sleep(5000) ' wait 5 seconds before trying again

                    End Try
                End If

                SyncLock Files.SharedObject
                    HasMoreItems = (Files.ToBeProcessed.Count > 0)
                End SyncLock
            Loop While HasMoreItems
            Files.MRE.WaitOne()
        End While
        'End If
    End Sub
    Private Sub bgw_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles bgw.ProgressChanged
        'If e.UserState.ToString.Contains("HD") Then HDList.Items.Add(Now.ToString() & " Processed " & e.UserState.ToString())
        'If e.UserState.ToString.Contains("FVOD") Then FVODList.Items.Add(Now.ToString() & " Processed " & e.UserState.ToString())
        'If e.UserState.ToString.Contains("15Mbps") Then IPVODList.Items.Add(Now.ToString() & " Processed " & e.UserState.ToString())
        'If e.UserState.ToString.Contains("HD") Or ("FVOD") Or ("15Mbps") Then BadLabel.ForeColor = Color.Green Else BadList.Items.Add(Now.ToString() & " Processed " & e.UserState.ToString())
        HDList.Items.Add(Now.ToString() & " Processed " & e.UserState.ToString())

    End Sub
    Public Class Files
        Public Shared ToBeProcessed As New Queue(Of String)
        Public Shared SharedObject As New Object
        Public Shared MRE As New System.Threading.ManualResetEvent(False)
    End Class
    Private m_WatchDirectory As String
    Private WithEvents m_FileSystemWatcher As FileSystemWatcher
    Private WithEvents bgw As New System.ComponentModel.BackgroundWorker


    Private Delegate Sub mProcessFileDelegate(ByVal file_name As String)
    ' Process a new file.
    Private Sub m_FileSystemWatcher_Created(ByVal sender As Object, ByVal e As System.IO.FileSystemEventArgs) Handles m_FileSystemWatcher.Created

        SyncLock Files.SharedObject
            If Not Files.ToBeProcessed.Contains(e.Name) Then
                Files.ToBeProcessed.Enqueue(e.Name)
                Files.MRE.Set()
            End If
        End SyncLock
    End Sub
    Private Function IsFileInUse(ByVal fileName As String) As Boolean

        Dim watchlocation As String
        watchlocation = "C:\Video\"

        Try
            Using fs As New FileStream(watchlocation & fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.None)
            End Using
            Return False
        Catch ex As Exception
            Debug.Print("IsFileInUse(): " & ex.ToString)
            Return True
        End Try
    End Function


    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        testlabel.Text = "StartLabel Button Pushed"
        StartLabel.Text = "Started"
        bgw.WorkerSupportsCancellation = True
        bgw.WorkerReportsProgress = True
        bgw.RunWorkerAsync()

        m_WatchDirectory = (m_WatchDirectory & "C:\Video\")

        ' Make the FileSystemWatcher.
        m_FileSystemWatcher = New FileSystemWatcher("C:\Video\", "*.mpg")
        m_FileSystemWatcher.NotifyFilter = 0
        m_FileSystemWatcher.NotifyFilter = m_FileSystemWatcher.NotifyFilter Or NotifyFilters.FileName
        m_FileSystemWatcher.EnableRaisingEvents = True

        testlabel.Text = "start Button Finished"
    End Sub
End Class

Open in new window

0
Comment
Question by:MaxDes101
10 Comments
 
LVL 69

Expert Comment

by:Éric Moreau
Comment Utility
0
 

Author Comment

by:MaxDes101
Comment Utility
I seem to have all of the required items from this article....
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
Comment Utility
Does m_FileSystemWatcher_Created() get fired when files get copied or moved to your folder?

You could add a Debug.Print() line in there to see:
    Private Sub m_FileSystemWatcher_Created(ByVal sender As Object, ByVal e As System.IO.FileSystemEventArgs) Handles m_FileSystemWatcher.Created



        Debug.Print("File Detected: " & DateTime.Now) ' <--- add a debug line



        SyncLock Files.SharedObject

            If Not Files.ToBeProcessed.Contains(e.Name) Then

                Files.ToBeProcessed.Enqueue(e.Name)

                Files.MRE.Set()

            End If

        End SyncLock

    End Sub

Open in new window

0
 

Author Comment

by:MaxDes101
Comment Utility
I think I found what the issue is. going to test now..
0
 

Accepted Solution

by:
MaxDes101 earned 0 total points
Comment Utility
fixed my own issue. took forever. It didn't like the way my if statements were setup...


If e.UserState.ToString.ToLower.Contains(hiDef.ToLower) Or e.UserState.ToString.ToLower.Contains(FVOD1.ToLower) Or e.UserState.ToString.ToLower.Contains(Fifteen.ToLower) Then
            GoodList.Items.Add(Now.ToString() & " Processed " & e.UserState.ToString())
        Else
            BadList.Items.Add(Now.ToString() & " Processed " & e.UserState.ToString())
        End If

Open in new window

0
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 
LVL 85

Expert Comment

by:Mike Tomlinson
Comment Utility
Glad you figured it out...but this statement is just silly:

    "I hit it right on the money and figured out my own issue before anyoen else managed to..."

There's no way we would have even guessed what the real problem was since your solution is "fixing" an area that in your original code was completely COMMENTED OUT:
*Plus your solution is using "GoodList" and "BadList" while the original was using "HDList"...   ?
   Private Sub bgw_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles bgw.ProgressChanged

        'If e.UserState.ToString.Contains("HD") Then HDList.Items.Add(Now.ToString() & " Processed " & e.UserState.ToString())

        'If e.UserState.ToString.Contains("FVOD") Then FVODList.Items.Add(Now.ToString() & " Processed " & e.UserState.ToString())

        'If e.UserState.ToString.Contains("15Mbps") Then IPVODList.Items.Add(Now.ToString() & " Processed " & e.UserState.ToString())

        'If e.UserState.ToString.Contains("HD") Or ("FVOD") Or ("15Mbps") Then BadLabel.ForeColor = Color.Green Else BadList.Items.Add(Now.ToString() & " Processed " & e.UserState.ToString())

        HDList.Items.Add(Now.ToString() & " Processed " & e.UserState.ToString())



    End Sub

Open in new window

0
 

Author Comment

by:MaxDes101
Comment Utility
I made a ton of changes since then.

But the issue was actually a different part of the code. lol. I had the wrong thing on the clipboard when I pasted in. See code snippet...


If FileName.Contains("15Mbps") Then
                            System.IO.File.Copy("C:\video\" & FileName, "X:\encoded2\mcvod\transcode_needed\" & FileName, True)

                        Else
                            System.IO.File.Copy("C:\video\" & FileName, "Z:\" & FileName, True)
                            System.IO.File.Copy("C:\video\" & FileName, "X:\Encoded2\" & FileName, True)

                        End If

was the following code:

If FileName.Contains("15Mbps") Then System.IO.File.Copy("C:\video\" & FileName, "X:\encoded2\mcvod\transcode_needed" & FileName, True) Else 
                        System.IO.File.Copy("C:\video\" & FileName, "Z:\" & FileName, True)
                        System.IO.File.Copy("C:\video\" & FileName, "X:\Encoded2\" & FileName, True)
                        If FileName.Contains("HD") Then HDList.Items.Add(FileName)
                        If FileName.Contains("FVOD") Then FVODList.Items.Add(FileName)
                        If FileName.Contains("15Mbps") Then IPVODList.Items.Add(FileName)
                        If FileName.Contains("HD") Or ("FVOD") Or ("15Mbps") Then BadLabel.ForeColor = Color.Green Else BadList.Items.Add(FileName)

Open in new window

0
 
LVL 85

Expert Comment

by:Mike Tomlinson
Comment Utility
That's a completely different part from the section your last solution was from!

You posted a fix for a section using "e.UserState" which should be in the ProgressChanged() event no?  That code is from the bgw.DoWork() handler.

Glad you figured it out on your owns as we would never have based on the code you posted...  =)

Give your clipboard a firm talking to!
0
 

Author Comment

by:MaxDes101
Comment Utility
Yeah thats why I mentioned I had posted the wrong snippet as my solution. I literally wrote the if statements both in the dowork area AND the other area 150 times to get them right. heh. It was crazy. regular nesting didn't work, it would run the first one and then stop... no clue why. so I changed them all. You WOULD have figured it out eventually.... as I did. It wasn't easy.
0
 
LVL 29

Expert Comment

by:nffvrxqgrcfqvvc
Comment Utility
LOL.. This has to be one of the best closing author comments of 2010. :)
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

This article describes relatively difficult and non-obvious issues that are likely to arise when creating COM class in Visual Studio and deploying it by professional MSI-authoring tools. It is assumed that the reader is already familiar with the cla…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

743 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now