The calling thread must be STA...

R

Rainer Queck

Hi NG,

I am currently exploring VS2008 and WPF.
In a very little WPF-Aplication I am using a System.Timers.Timer and
assigned a Eventhandler to its "Elapsed" event.

When the eventhandler is called, I receive the following error message:
The calling thread must be STA, because many UI components require this.

I assum I need to synchronize the call with the GUI some how.
In Winform applications I used this.InvokeRequred to detect the neccessary
to do so and the used this.Invoke.

How would I do this with a WPF application now?

Thanks for hints and help.

Regards
Rainer Queck
 
J

Jon Skeet [C# MVP]

I am currently exploring VS2008 and WPF.
In a very little WPF-Aplication I am using a System.Timers.Timer and
assigned a Eventhandler to its "Elapsed" event.

When the eventhandler is called, I receive the following error message:
The calling thread must be STA, because many UI components require this.

I assum I need to synchronize the call with the GUI some how.
In Winform applications I used this.InvokeRequred to detect the neccessary
to do so and the used this.Invoke.

How would I do this with a WPF application now?

See http://msdn.microsoft.com/msdnmag/issues/07/10/WPFThreading/default.aspx

Jon
 
W

Willy Denoyette [MVP]

Rainer Queck said:
Hi NG,

I am currently exploring VS2008 and WPF.
In a very little WPF-Aplication I am using a System.Timers.Timer and
assigned a Eventhandler to its "Elapsed" event.

When the eventhandler is called, I receive the following error message:
The calling thread must be STA, because many UI components require this.

I assum I need to synchronize the call with the GUI some how.
In Winform applications I used this.InvokeRequred to detect the neccessary
to do so and the used this.Invoke.

How would I do this with a WPF application now?

Thanks for hints and help.

Regards
Rainer Queck

Take a look at the Dispatcher.Invoke method in System.Windows.Threading.

Willy.
 
R

Roman Wagner

In WPF you should use the Dispatcher Property to start any async
operations.
See the following example the variable _lbl is a label of my form.

public partial class Window1 : System.Windows.Window
{
private Timer _timer = new Timer(1000);

private delegate void DummyDelegate();

public Window1()
{
InitializeComponent();
_timer.Elapsed += delegate
{
this.Dispatcher.Invoke(
System.Windows.Threading.DispatcherPriority.Normal,
(DummyDelegate)
delegate { _lbl.Content = DateTime.Now.ToLongTimeString(); });
};
_timer.Start();
}

}
 
R

Rainer Queck

Hi Jon, Willy, Roman,

Thanks for your hints. I have my little app working now.

Regards
Rainer
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top