我需要我的WPF exe一旦启动就开始监视队列,然后在消息进入时响应。
我现在的方式是:
public partial class App
{
readonly BackgroundWorker _worker = new BackgroundWorker();
protected override void OnStartup(StartupEventArgs e)
{
_worker.DoWork += worker_DoWork;
_worker.RunWorkerCompleted += worker_RunWorkerCompleted;
_worker.RunWorkerAsync();
}
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
_worker.DoWork += worker_DoWork;
_worker.RunWorkerAsync();
}
static void worker_DoWork(object sender, DoWorkEventArgs e)
{
//do work
}
显然,这是非常可怜的IMO。
另外,我不喜欢在线程中使用while(true)
的方法来保持它无限期地运行..
答案 0 :(得分:0)
从队列中读取消息不是永久性的,而是定期读取的 常见的方法是使用计时器。例如,System.Threading.Timer。
public partial class App : Application
{
private System.Threading.Timer _msmqReadTimer;
public App()
{
_msmqReadTimer = new System.Threading.Timer(MsmqReadTimerTick);
_msmqReadTimer.Change(0, 1000); // call MsmqReadTimerTick immediatelly and each 1000 ms
}
private void MsmqReadTimerTick(object state)
{
// do work
// if you want to update some UI components after work, you should post this to UI thread dispatcher:
this.Dispatcher.Invoke(()=>
{
// logic for updating UI should be here
},
System.Windows.Threading.DispatcherPriority.Background);
}
}