?
Solved

Cross threading error in VB.net

Posted on 2010-01-11
2
Medium Priority
?
853 Views
Last Modified: 2012-05-08
I get an error when trying to run my program:
Cross-thread operation not valid: Control 'lstFiles' accessed from a thread other than the thread it was created on.

Now I know i need to invoke somehow, but I am lost as to how to do this. How can I fix this cross threading issue in my software and how can I have file_name NOT include the entire path in it?
Imports System.IO

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
            Return p.ExitCode
        Catch e As System.Exception
            'Catch errors here
        End Try
    End Function

#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call

    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    Friend WithEvents lstFiles As System.Windows.Forms.ListBox
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.lstFiles = New System.Windows.Forms.ListBox
        Me.SuspendLayout()
        '
        'lstFiles
        '
        Me.lstFiles.Dock = System.Windows.Forms.DockStyle.Fill
        Me.lstFiles.Location = New System.Drawing.Point(0, 0)
        Me.lstFiles.Name = "lstFiles"
        Me.lstFiles.Size = New System.Drawing.Size(1025, 368)
        Me.lstFiles.TabIndex = 0
        '
        'Form1
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(1025, 372)
        Me.Controls.Add(Me.lstFiles)
        Me.Name = "Form1"
        Me.Text = "Form1"
        Me.ResumeLayout(False)

    End Sub

#End Region

    Private m_WatchDirectory As String
    Private WithEvents m_FileSystemWatcher As FileSystemWatcher

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'lstFiles.Items.Add(Now.ToString() & " Starting")

        ' Get the path to the directory we will watch.
        'm_WatchDirectory = Application.StartupPath
        'm_WatchDirectory = m_WatchDirectory.Substring(0, m_WatchDirectory.LastIndexOf("\"))
        m_WatchDirectory &= "c:\docume~1\user\desktop\howtofolderwatcher\baton\bad"

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

        ' Process any files that already exist.
        'ProcessExistingFiles(m_WatchDirectory)
    End Sub

    ' Process a new file.
    Private Sub m_FileSystemWatcher_Created(ByVal sender As Object, ByVal e As System.IO.FileSystemEventArgs) Handles m_FileSystemWatcher.Created
        ProcessFile(e.Name)
    End Sub

    ' Process existing files.
    'Private Sub ProcessExistingFiles(ByVal directory_name As String)
    'Dim dir_info As New DirectoryInfo(directory_name)
    'Dim file_infos As FileInfo() = dir_info.GetFiles()
    'For Each fi As FileInfo In file_infos
    'ProcessFile(fi.FullName)
    'Next fi
    ' End Sub

    ' Process a file.
    Private Sub ProcessFile(ByVal file_name As String)
        lstFiles.Items.Add(Now.ToString() & " Processed " & file_name)
        ExecCommand("cmd", " /c " & "c:\docume~1\user\desktop\howtofolderwatcher\baton\bad\dtrmxutil.exe " & file_name & " nulls" & file_name & " 6000000", Waitforexit:=True)

    End Sub

End Class

Open in new window

0
Comment
Question by:cpservice
[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
2 Comments
 
LVL 27

Accepted Solution

by:
VBRocks earned 2000 total points
ID: 26286599
Do it like this:

    'Create a delegate
    Private Delegate Sub mProcessFileDelegate(ByVal file_name As String)

    Private Sub ProcessFile(ByVal file_name As String)

        If lstFiles.InvokeRequired Then

            Dim d As New mProcessFileDelegate(AddressOf ProcessFile)
            lstFiles.Invoke(d, New Object() {file_name})

        Else

            lstFiles.Items.Add(Now.ToString() & " Processed " & file_name)
            'ExecCommand...

        End If


    End Sub

0
 

Author Closing Comment

by:cpservice
ID: 31675687
PERFECT
0

Featured Post

Get real performance insights from real users

Key features:
- Total Pages Views and Load times
- Top Pages Viewed and Load Times
- Real Time Site Page Build Performance
- Users’ Browser and Platform Performance
- Geographic User Breakdown
- And more

Question has a verified solution.

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

When we want to run, execute or repeat a statement multiple times, a loop is necessary. This article covers the two types of loops in Python: the while loop and the for loop.
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
This video teaches viewers about errors in exception handling.
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
Suggested Courses

771 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