Pablo Fernandez
Pablo Fernandez

Reputation: 105210

Calling a windows form from another thread (.Net)

Hi I'm developing a .Net application and I want to achieve the following:

I have a winforms application, and a timer (System.Timers.timer) that excecutes a thread based on a schedule. The problem is that I cannot access the UI (windows form) from the secondary thread (WorkerThread), the error say something like the component cannot be accessed from a thread that didn't create it.

Is there any way to achieve this?

Thanks!

Upvotes: 5

Views: 1853

Answers (2)

Serhat Ozgel
Serhat Ozgel

Reputation: 23766

Let's say that your worker method (that you execute in a thread) is

DoWork(args)
{
    ...
    UpdateUI();
}

The method that handles timer's Elapsed event should do this:

OnTimerElapsed(object sender, ElapsedEventArgs e)
{
    args = GetArgs();
    this.BeginInvoke(() => DoWork(args));
    // 'this' refers to form here.
    // You can also use BeginInvoke on a user control for updating it.
}

This will run DoWork in a seperate thread and DoWork will have the ability of updating UI.

Upvotes: 2

Mehrdad Afshari
Mehrdad Afshari

Reputation: 421968

 formObject.Invoke(delegate { 
      // action to perform on UI thread
 });

Upvotes: 10

Related Questions