Click here to Skip to main content
15,895,084 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Recently I developing a IM software, and want to dynamics add a tab page on the form when a new private chat request is arrived, but I have a problem about .NET is not allowed me to add a control when the code is running cross threads.

I have try using delegate to invoke this cross thread action, but it still not works....

Now I have no idea about this problem.

Here is the code how i dynamics add a control.

VB
''' <summary>
''' 函数返回Key,添加的新的标签页控件的哈希值,不能够跨线程添加控件
''' Dynamics add a tabpage control on the form 
''' </summary>
''' <returns></returns>
''' <remarks></remarks>
Public Function Add(Control As Control) As Integer
    Dim Panel As PagePanel = New PagePanel

    ControlToAdd = Panel

    SyncLock ControlToAdd

        Call _InternalForm.Invoke(New MethodInvoker(AddressOf AddControlInvoke))

        ControlAddToPanel = Control

        SyncLock ControlAddToPanel

            Call ControlToAdd.Invoke(New MethodInvoker(AddressOf PanelAddControlInvoke)) ' !!! The code stuck running at here.

        End SyncLock

    End SyncLock

    Call Panel.Controls.Add(Control)
    Control.Dock = DockStyle.Fill

    Dim Key As Integer = Panel.GetHashCode()
    Call Add(Key, Panel)
    Call [Select](Panel)

    Return Key
End Function

Dim ControlToAdd As PagePanel
Dim ControlAddToPanel As Control

Private Sub PanelAddControlInvoke()
    Call ControlToAdd.Controls.Add(ControlAddToPanel)
End Sub

Private Sub AddControlInvoke()
    Call _InternalForm.Controls.Add(ControlToAdd)
End Sub
Posted

1 solution

If you are using WinForms then:
C#
control.BeginInvoke(...);

If you are using xaml then:
C#
control.Dispatcher.BeginInvoke(...);
 
Share this answer
 
Comments
Mr. xieguigang 谢桂纲 6-May-15 11:32am    
Control.BeginInvoke(MethodInvoker) is still not working... the code is still stuck running at here
InbarBarkai 6-May-15 23:48pm    
You're locking the panel before using it on another place.
That's why you get a deadlock.
The SyncLock command prevents any other thread from using the object. Since you start a new thread to add the control, it tries to access the panel but stops because of the lock.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900