Solved

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

Posted on 2010-09-01
10
591 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 70

Expert Comment

by:Éric Moreau
ID: 33579053
0
 

Author Comment

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

Expert Comment

by:Mike Tomlinson
ID: 33579357
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
Resolve Critical IT Incidents Fast

If your data, services or processes become compromised, your organization can suffer damage in just minutes and how fast you communicate during a major IT incident is everything. Learn how to immediately identify incidents & best practices to resolve them quickly and effectively.

 

Author Comment

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

Accepted Solution

by:
MaxDes101 earned 0 total points
ID: 33581296
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
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 33581817
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
ID: 33581875
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
ID: 33581898
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
ID: 33581921
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
ID: 33582431
LOL.. This has to be one of the best closing author comments of 2010. :)
0

Featured Post

Webinar: Aligning, Automating, Winning

Join Dan Russo, Senior Manager of Operations Intelligence, for an in-depth discussion on how Dealertrack, leading provider of integrated digital solutions for the automotive industry, transformed their DevOps processes to increase collaboration and move with greater velocity.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Write to a printer using vb.net 9 38
Get distinct values from excel or comm seperated file 4 30
ASP.NET (VB) return a record 2 35
VB.NET Textbox input validation 4 37
Welcome my friends to the second instalment and follow-up to our Minify and Concatenate Your Scripts and Stylesheets (http://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/A_4334-Minify-and-Concatenate-Your-Scripts-and-Stylesheets.html)…
It’s quite interesting for me as I worked with Excel using vb.net for some time. Here are some topics which I know want to share with others whom this might help. First of all if you are working with Excel then you need to Download the Following …
Established in 1997, Technology Architects has become one of the most reputable technology solutions companies in the country. TA have been providing businesses with cost effective state-of-the-art solutions and unparalleled service that is designed…
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

808 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