Java and C# : Control update in a way of thread safe

Now I know in C#, if one control was created in one thread(the main thread for example), but if you want to update the control in another thread, You can not update it directly, you need to use like Invoke method, otherwise, it will report error.

I have piece of code below, which now is thread safe after benchmark several articles in this side, and the micro soft online SDK document.

But in Java form –JFrame, it looks different, you can manipulate the control in separate thread directly ,that is no problem.

I have development experience in National Instrument CVI also, manipulate the control in separate thread directly also has no problem.

So,
Why in C# or .NET ,the control is so thread sensitive, deal with in special way?
  

//Define in one form class
public delegate void AddListItem(String myString);
public AddListItem myDelegate;

myDelegate = new AddListItem(Update_List);//In form constructor


public void Update_List(string myString)
{
   Listbox1.Add(myString);
}

/////execute in another thread, which class have one instance variable ‘parent_form’ of the form.

    while(!Thread_Stop)
    {
       string myString= DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss_fff");

     try
     {
      parent_form.Invoke( parent_form.myDelegate, new Object[] {myString}); 
      Thread.Sleep(100);
     }
    catch
    {
    }
  }

  • 1

    Updating controls in java swing with another thread is not ok in general. Except for specific exceptions updates should be made on the event dispatch thread.

    – 

  • I know of no UI framework where you can update the UI outside of THE UI thread.

    – 

Leave a Comment