Hey all,
I'm trying to change/execute the example http://www.codeproject.com/KB/thread...onContext.aspx
I think the problem may be in my translation to Vb....
I've posted my project below. I'm getting a cross-threading error and I thought the point of all of this was to avoid that. (yes I realize I could just delegate... I'm trying to do something more complicated but am using this as a test bed)
Thanks in advance...
The following is just a form with a button and list box.
Code:Imports System.Threading.Thread Imports System.Threading Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click ' let's see the thread id Dim id As Integer Dim uiContext As SynchronizationContext Dim thread As Thread id = thread.CurrentThread.ManagedThreadId Trace.WriteLine("Button1_Click thread: " + id.ToString) ' grab the sync context associated to this ' thread (the UI thread), and save it in uiContext ' note that this context is set by the UI thread ' during Form creation (outside of your control) ' also note, that not every thread has a sync context attached to it. uiContext = SynchronizationContext.Current ' create a thread and associate it to the run method thread = New Thread(AddressOf Run) ' start the thread, and pass it the UI context, ' so this thread will be able to update the UI ' from within the thread thread.Start(uiContext) End Sub Private Sub Run(ByVal state As Object) Dim id As Integer Dim uiContext As SynchronizationContext id = thread.CurrentThread.ManagedThreadId Trace.WriteLine("Run thread: " + id.ToString) ' grab the context from the state uiContext = state For i = 0 To 1000 Thread.Sleep(10) ' use the ui context to execute the UpdateUI method, ' this insure that the UpdateUI method will run on the UI thread. uiContext.Post(UpdateUI(state), "line " + i.ToString()) Next End Sub Private Function UpdateUI(ByVal state As Object) Dim id As Integer Dim text As String id = Thread.CurrentThread.ManagedThreadId Trace.WriteLine("UpdateUI thread:" + id.ToString) text = state.ToString mListBox.Items.Add(text) Return "" End Function End Class




Reply With Quote