Solved

Multithreading, how to access property on the new form

Posted on 2006-07-18
8
311 Views
Last Modified: 2011-09-20
Hi experts

i have a main form that launch many other forms

so i do that :

on click button to launch a new form

Dim nThread As New Thread(AddressOf newThread)
        nThread.Name = Me.txtBxComputerName.Text & "_" & Me.TreeView.SelectedNode.Text
        MyThreads.Add(nThread) 'arraylist
        nThread.Start()

the sub :

Private Sub newThread()
        Dim frm As New MainReader 'the form to load

        frm.setComputerName = Me.txtBxComputerName.Text.Trim

        frm.setSelectedQueue = Me.TreeView.SelectedNode.Text

        Try
            Application.Run(frm)
        Catch ex As System.InvalidOperationException
            ' description :A main message loop is already running on this thread.
            MsgBox("Cannot open the reader : " & ex.Message)
        End Try
    End Sub

i have an exception on these lines :

 frm.setComputerName = Me.txtBxComputerName.Text.Trim

        frm.setSelectedQueue = Me.TreeView.SelectedNode.Text

illegal cross...

so i set Control.CheckForIllegalCrossThreadCalls on False

but i'm sure that theres is a better solution to access property of a new form

can you help me please?

kind regards
0
Comment
Question by:Dnx_7
8 Comments
 
LVL 6

Expert Comment

by:Nandakumar Sakthivel
ID: 17136474

Can u post me the complete error message  with stack trace

Thanks,
Nanda
0
 
LVL 2

Author Comment

by:Dnx_7
ID: 17136494
System.InvalidOperationException was unhandled
  Message="Cross-thread operation not valid: Control 'TreeView' accessed from a thread other than the thread it was created on."
  Source="System.Windows.Forms"
  StackTrace:
       at System.Windows.Forms.Control.get_Handle()
       at System.Windows.Forms.Control.SendMessage(Int32 msg, Int32 wparam, Int32 lparam)
       at System.Windows.Forms.TreeView.get_SelectedNode()
       at AutomationReader.frmMain.newThread() in C:\Projet .NET\AutomationReader\AutomationReader\frmMain.vb:line 191
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.runTryCode(Object userData)
       at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()

regards
0
 
LVL 19

Expert Comment

by:arif_eqbal
ID: 17136767
Hi Dnx_7
you can't access controls like this from a new thread, the Controls are in a separate UI thread and they are not directly accessible from outside the Thread boundary
you need to pass arguments to your Thread Function so that the Properties can be set

Try something like this

Public Class ThreadData
     Public ComputerName As String
     Public SelectedQueue As String

     Public Sub newThread()
        Dim frm As New MainReader
        frm.setComputerName = ComputerName
        frm.setSelectedQueue = SelectedQueue
        Try
            Application.Run(frm)
        Catch ex As System.InvalidOperationException
            ' description :A main message loop is already running on this thread.
            MsgBox("Cannot open the reader : " & ex.Message)
        End Try
    End Sub
End Class

Then to call it

    Dim ThData As New ThreadData
    ThData.ComputerName = Me.txtBxComputerName.Text.Trim
    ThData.setSelectedQueue = Me.TreeView.SelectedNode.Text

    Dim nThread As New Thread(AddressOf ThData.newThread)
    nThread.Name = Me.txtBxComputerName.Text & "_" & Me.TreeView.SelectedNode.Text
    MyThreads.Add(nThread)
    nThread.Start()


#I have typed out the code here so take care of some Typo or some silly mistake :-)
0
Are your AD admin tools letting you down?

Managing Active Directory can get complicated.  Often, the native tools for managing AD are just not up to the task.  The largest Active Directory installations in the world have relied on one tool to manage their day-to-day administration tasks: Hyena. Start your trial today.

 
LVL 6

Accepted Solution

by:
Nandakumar Sakthivel earned 250 total points
ID: 17136812

I think that the problem is for some operations we cannot access the particular control from the thread other that the created thread

for that declare a delegate and a function like this in the main thread (Not in the newthread() function)

Private Delegate Sub UpdateSelectedQueue(ByVal classname As object)

Private sub UpdateQueue(byval classname as object)
   ctype(classname ,MainReader ).MyComputerName= Me.TreeView.SelectedNode.Text
end sub

In the newthread() function just replace the code like this

Private Sub newThread()
        Dim frm As New MainReader 'the form to load
        frm.setComputerName = Me.txtBxComputerName.Text.Trim
       
         ====>  Dim UpdateQueueDlg As New UpdateSelectedQueue(AddressOf UpdateQueue)
         ====>  Me.Invoke(UpdateQueueDlg, New Object() {frm})
        Try
            Application.Run(frm)
        Catch ex As System.InvalidOperationException
            ' description :A main message loop is already running on this thread.
            MsgBox("Cannot open the reader : " & ex.Message)
        End Try
    End Sub

What i am doing is I am trying to access the value of the treeview in the main thread itself  by using the Invoke() method in the NewThread() by using delegates

Hope this helps
Thanks,
Nanda
0
 
LVL 24

Assisted Solution

by:Jeff Certain
Jeff Certain earned 250 total points
ID: 17137448
Okay... there are two options. If you're getting this error, it means that you are using Visual Studio 2005. Each control has a property called CheckForIllegalCrossThreadCalls. If you set this to false for the control you're trying to update, the issue will be resolved.

Alternately, you can use the Invoke approach (as Nanda indicated). Usually I take a slightly different approach than Nanda, however; I create a new routine to handle the control update, and check if the Invoke is actually required.

  Private Delegate Sub AddItemCallback(ByVal message As String)
  Private Sub AddItem(ByVal message As String)
    If Me.ListBox1.InvokeRequired Then
      Dim d As New AddItemCallback(AddressOf AddItem)
      Me.Invoke(d, New Object() {message})
    Else
      Me.ListBox1.Items.Add(message)
    End If
  End Sub
0
 
LVL 24

Expert Comment

by:Jeff Certain
ID: 17323217
My two cents worth? 20/80 split between Nanda and Arif.
0

Featured Post

Ransomware: The New Cyber Threat & How to Stop It

This infographic explains ransomware, type of malware that blocks access to your files or your systems and holds them hostage until a ransom is paid. It also examines the different types of ransomware and explains what you can do to thwart this sinister online threat.  

Question has a verified solution.

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

This article explains how to create and use a custom WaterMark textbox class.  The custom WaterMark textbox class allows you to set the WaterMark Background Color and WaterMark text at design time.   IMAGE OF WATERMARKS STEPS Create VB …
Article by: Kraeven
Introduction Remote Share is a simple remote sharing tool, enabling you to see, add and remove remote or local shares. The application is written in VB.NET targeting the .NET framework 2.0. The source code and the compiled programs have been in…
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…
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…

773 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