troubleshooting Question

Small app error: InvalidOperationException was unhandled

Avatar of wally_davis
wally_davisFlag for United States of America asked on
Visual Basic.NET
4 Comments1 Solution729 ViewsLast Modified:
I have a VB.NET Windows form that has two buttons and a textbox.
One button will just open and read a text file and perform an Asynchronous operation and display text. (So, I've just written the routine for the buttonReadAsync_Click event and need to get the error resolved before moving onto the second button)
Second button will open and readt a text file and perform a Synchronous operation.

I'm still working on how to understand threading and don't quite have the hang of it yet. I've described what the error is below and where it happens in my code.
I would appreciate an explanation on what I missed and why it threw this error.
Option Explicit On
Option Strict On
Imports System.IO
Imports System.Text
Imports System.Threading
Public Class MainForm
    Dim fs As System.IO.FileStream
    Dim fileContents As Byte()
    Dim callBack As AsyncCallback
    Private Sub buttonReadAsync_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles buttonReadAsync.Click
        callBack = New AsyncCallback(AddressOf fs_StateChanged)
        fs = New System.IO.FileStream(OpenFileDialog1.FileName, _
            IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read, 4096, IO.FileOptions.None)
        ReDim fileContents(CInt(fs.Length))
        fs.BeginRead(fileContents, 0, CInt(fs.Length), callBack, Nothing)
    End Sub <-- AFTER THIS LINE IS PROCESSED IT THROWS THE ERROR "Cross-thread operation not valid: Control 'textBoxResults' accessed from a thread other than the thread it was created on.
    Private Sub fs_StateChanged(ByVal AsyncResult As IAsyncResult)
        If AsyncResult.IsCompleted Then
            textBoxResults.Text = Encoding.UTF8.GetString(fileContents)
        End If
    End Sub
End Class
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 4 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 4 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros