|
I have an application which is near complete, but I never thought it would get this big or desired. The application reads a folder with files in it for user settings, then waits for user input. When input is started, it does specific searches online. When it is doing these searches, the application appears frozen until it finds what the user was looking for and prompts the user for input.
I have tried a few ways to get threading into this, but everytime I get the problem similar to the following.
Cross-thread operation not valid: Control 'ProgressBar1' accessed from a thread other than the thread it was created on.
I tried starting a new thread within the application following http://www.codeproject.com/Articles/15861/How-to-solve-quot-Cross-thread-operation-not-valid and I still get the same problem.
How can I turn my single threaded application into a multiple threaded application?
I am using vb.net 2008
|
|
|
|
|
A thread is a new process started by u and it can not access controls of thread who create it. but the child thread can return data to parent thread.
error "Cross-thread operation not valid: Control 'ProgressBar1' accessed from a thread other than the thread it was created on" thrown by your code is an example of it.
Solution: you can use BackgroundWorker class to reduce your problem. it will start a new thread and doesn't hang your application while searching and it can also return data to your application after completion of it's execution.
if you can work according to my suggesion then OK otherwise tell me, i will give an example code that will solve your problem.
|
|
|
|
|
The Invoke pattern;
Imports System.Threading
Public Class Form1
Dim MyNewThread As Thread
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
MyNewThread = New Thread(AddressOf MyThread.MyThreadExecute)
MyThread.ThatForm = Me
MyNewThread.Start()
End Sub
Public Sub SetProgress(ByVal What As String)
If InvokeRequired Then
Invoke(New Action(Of String)(AddressOf SetProgress), New Object() {What})
Return
End If
Label1.Text = What
End Sub
End Class
Module MyThread
Public ThatForm As Form1
Public Sub MyThreadExecute()
Dim i As Integer = 0
Do
i = i + 1
ThatForm.SetProgress(i)
Thread.Sleep(100)
Loop
End Sub
End Module
|
|
|
|