我需要实现一个功能,每1分钟请求一次服务器,如果服务器有消息则弹出消息窗体。
我尝试代码如下:
private static System.Timers.Timer CheckNotificationTimer = new System.Timers.Timer();
public MainForm()
{
InitializeComponent();
CheckNotificationTimer.Interval = 2000;
CheckNotificationTimer.Enabled = true;
CheckNotificationTimer.Elapsed += new System.Timers.ElapsedEventHandler(CheckNotificationTimer_Elapsed); CheckNotificationTimer.AutoReset = true; }
private static void CheckNotificationTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
NotificationForm form = new NotificationForm();
int x = Screen.PrimaryScreen.WorkingArea.Right - form.Width;
int y = Screen.PrimaryScreen.WorkingArea.Bottom - form.Height;
form.Location = new Point(x, y);
form.Show();
//KryptonMessageBox.Show("xxx")
}
当执行弹出NotificationForm 时,NotificationForm 是卡死的,貌似是线程阻塞了,我应该怎样实现这样的功能需求呢?
谢谢
使用Backgroundworker组件,然后用下面的两个事件来操作
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { //1、这里做很复杂的事情,这个里面可以把线程暂停掉,不会影响到界面的操作的,可以用下面的方法来实现timer的暂停时间控制 Thread.Sleep(1000); } private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { //2、做完后会调用这个事件 //3、下面的代码可以帮助你实现循环调用 backgroundWorker1.RunWorkerAsync(); }
请用Backgroundworker
采用委托的方式弹窗。
private delegate void Test(); private readonly Timer timer = new Timer { Enabled = true, Interval = 3000 }; private Alert alert; public Form1() { InitializeComponent(); timer.Elapsed += timer_Elapsed; } private void timer_Elapsed(object sender, ElapsedEventArgs e) { if (this.InvokeRequired) { this.BeginInvoke(new Test(ShowBox)); } } private void ShowBox() { if (alert == null) { alert = new Alert(); } alert.Show(); } Alert是一个新窗体。