How to update streaming management in a secure way

I have a windows.form.userControl class, and at runtime I want to add some reference tags dynamically. When I apply this piece of code inside the Load method, it works fine.

for (int i = 0; i < 10; i++)
     {
       linkLabel = new System.Windows.Forms.LinkLabel();
       linkLabel.Name = i.ToString();
       linkLabel.Text = i.ToString();
       linkLabel.LinkClicked += new  System.Windows.Forms.LinkLabelLinkClickedEventHandler(linkLabel_LinkClicked);
       this.Controls.Add(linkLabel);
       linkLabel.Top = top;
       top += 30;
      }

But when I move this piece of code inside the backgroudworker doWork method , it will give an invalid statement related to the cross-thread problem on this line: - . Controls.Add (LinkLabel);

How to make this a safe thread? I am new to C # and I am using C # 4.0 using VS 2010. Thanks in advance.

+3
source share
4 answers

. Control.InvokeRequired Control.Invoke .

private void AddLinkLabels()
{
    // If synchronization is needed, i.e. when this method is called on a non-UI thread, invoke the method synchronized and return immediately.
    if(InvokeRequired)
    {
        Invoke(new MethodInvoker(AddLinkLabels));
        return;
    }

    for (int i = 0; i < 10; i++)
    {
        linkLabel = new System.Windows.Forms.LinkLabel();
        linkLabel.Name = i.ToString();
        linkLabel.Text = i.ToString();
        linkLabel.LinkClicked += new  System.Windows.Forms.LinkLabelLinkClickedEventHandler(linkLabel_LinkClicked);
        this.Controls.Add(linkLabel);
        linkLabel.Top = top;
        top += 30;
    }
}
+3

, , .

if(this.InvokeRequired)
   this.Invoke(new Action(() => {this.Controls.Add(linkLabel);}));
else
   this.Controls.Add(linkLabel); 
+6

Stecya , .

+1

As Stecya has said: you must switch to the thread that this control created to interact with it. This can be done in the ProgressChanged event for the background, because it works in the UI thread, without having to make a call. Sample on MSDN .

0
source

All Articles