计时器结束并尝试显示新 Window C# 时出错

Error when timer is elapsed and trying to show new Window C#

我的简单应用程序中有一个计时器:

        System.Timers.Timer aTimer = new System.Timers.Timer();
        aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
        aTimer.Interval = 3000;
        aTimer.Enabled = true;

每次调用此函数已过

    private static void OnTimedEvent(object source, ElapsedEventArgs e)
    {
        ...
        DisplayWindow displayedWindow = new DisplayWindow();
        displayedWindow.Show();
        ...
    }

displayedWindow 是一个 WPF 表单,它只有创建的代码本身(和我的关闭按钮):

public partial class DisplayWindow : Window
{
    public DisplayWindow()
    {
        InitializeComponent();
    }

    private void cancelButton_Click(object sender, RoutedEventArgs e)
    {
        this.Close();
    }
}

当我 运行 我的应用出现错误时

public DisplayWindow()

其中有这样的消息:

 "The calling thread must be STA, because many UI components require this".

我正在尝试阅读一些线程,而我刚刚发现是在玩 STA Thread,但没有成功。 我该如何解决这个问题?

If a System.Timers.Timer is used in a WPF application, it is worth noting that the System.Timers.Timer runs on a different thread then the user interface (UI) thread. In order to access objects on the user interface (UI) thread, it is necessary to post the operation onto the Dispatcher of the user interface (UI) thread using Invoke or BeginInvoke. Reasons for using a DispatcherTimer opposed to a System.Timers.Timer are that the DispatcherTimer runs on the same thread as the Dispatcher and a DispatcherPriority can be set on the DispatcherTimer.

考虑为此使用 DispatcherTimer :

var timer = new DispatcherTimer();
timer.Tick += OnTimedEvent;
timer.Interval = TimeSpan.FromSeconds(3);
timer.Start();

并且,将您的处理程序签名更改为:

private static void OnTimedEvent(object sender, EventArgs e)

在计时器事件中需要 UI 调用您的方法,而不是当场调用它。 UI 线程将稍后 尽快调用您的方法。

这是取自 MSDN 的示例。我留给你相应地调整你的定时器处理程序:

if (this.textBox1.InvokeRequired)
{   
    SetTextCallback d = new SetTextCallback(SetText);
    this.Invoke(d, new object[] { text });
}
else
{
    this.textBox1.Text = text;
}