C# PopupNotifier在计时器类中不工作
C# PopupNotifier在计时器类中不工作,c#,wpf,timer,C#,Wpf,Timer,PopupNotifier不工作,当它被放置在timer类中时,如果我们将PopupNotifier放在timer类之外,它对我来说工作正常,下面的代码用于此 public MainWindow() { InitializeComponent(); bool needToShowInTaskbar = this.ShowInTaskbar; WindowState initialWindowState = t
PopupNotifier
不工作,当它被放置在timer类
中时,如果我们将PopupNotifier
放在timer类之外,它对我来说工作正常,下面的代码用于此
public MainWindow()
{
InitializeComponent();
bool needToShowInTaskbar = this.ShowInTaskbar;
WindowState initialWindowState = this.WindowState;
// making window invisible
this.ShowInTaskbar = false;
this.WindowState = WindowState.Minimized;
// showing and hiding window
this.Show();
this.Hide();
// restoring original settings
this.ShowInTaskbar = needToShowInTaskbar;
this.WindowState = initialWindowState;
SetTimer();
}
private void SetTimer()
{
m_mainTimer = new System.Timers.Timer();
m_mainTimer.Interval = 60000; // every one min
m_mainTimer.Elapsed += m_mainTimer_Elapsed;
m_mainTimer.AutoReset = false; // makes it fire only once
m_mainTimer.Start(); // Start
m_timerTaskSuccess = false;
}
private void m_mainTimer_Elapsed(Object source, ElapsedEventArgs e)
{
try
{
LoadData();
PopupNotifier popup = new PopupNotifier();
popup.TitleText = joomla.subject;
popup.ContentText = joomla.body;
popup.Popup();
m_timerTaskSuccess = true;
}
catch (Exception ex)
{
m_timerTaskSuccess = false;
}
finally
{
if (m_timerTaskSuccess)
{
m_mainTimer.Start();
}
}
}
将计时器更改为
System.Windows.Threading.dispatchermer
时,它对我来说运行良好
private void SetTimer()
{
dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, 60);
dispatcherTimer.Start();
}
“不起作用”不足以描述问题。您是否希望我们运行您的代码时看到异常或其他问题?
System.Timers.Timer
从线程池线程而不是主UI线程进行回调。您可能需要使用BeginInvoke()
调用执行LoadData()
的方法以及当前在try/catch中的其余代码。或者您可以尝试使用System.Windows.Threading.dispatchermer
而不是System.Timers.Timer
@TimSchmelter,我会问这个问题为什么它不工作,这意味着方法调用中是否存在任何问题,对我来说,调试时没有显示任何异常或任何其他问题。@Matthew Watson感谢它为我提供的解决方案,我已将该解决方案作为答案放置。删除exception eating catch子句以查看实际发生的错误如何?