您的位置:首页 > 其它

System.Timers.Timer与System.Windows.Forms.Timer比较

2010-11-20 23:26 281 查看
为了搞清楚这两个控件的性能区别,我编写了实验程序。

下面是System.Timers.Timer的实验程序

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace WindowsFormsApplication6
{
public partial class Form1 : Form
{
private delegate void TextBoxSetDelegate(string str);
private System.Timers.Timer timer1 = new System.Timers.Timer();
public Form1()
{
InitializeComponent();
timer1.Interval = 1000;
timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Elapsed);
timer1.Enabled = true;
CheckForIllegalCrossThreadCalls = false;
}

private void TextBoxSet(string str)
{
textBox1.Text = str;
richTextBox1.Text += DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "  " + textBox1.Text + "/r/n";
}

void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (textBox1.InvokeRequired)
{
TextBoxSetDelegate d = new TextBoxSetDelegate(TextBoxSet);
this.Invoke(d, new object[] { int.Parse(textBox1.Text) + 1 + "" });
}
else
{
textBox1.Text = int.Parse(textBox1.Text) + 1 + "";
richTextBox1.Text += DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "  " + textBox1.Text + "/r/n";
}
}

private void button1_Click(object sender, EventArgs e)
{
Thread.Sleep(10000);
}
}
}


在TextBox运行到3时点击“Stop”按钮,运行结果如下图



从结果来看,线程的占用是会影响到System.Timers.Timer的触发时间的,但触发次数不会受影响。

你可能会发现,这个程序中使用了Invoke。如果不使用,“Stop”按钮的响应函数执行完程序会在运行“textBox1.Text = int.Parse(textBox1.Text) + 1 + "";”时textBox1.Text会抛出Microsoft.VisualStudio.Debugger.Runtime.CrossThreadMessagingException异常。

下面是System.Windows.Forms.Timer的实验程序

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace WindowsFormsApplication6
{
public partial class Form1 : Form
{
private System.Windows.Forms.Timer timer1 = new System.Windows.Forms.Timer();
public Form1()
{
InitializeComponent();
timer1.Interval = 1000;
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Enabled = true;
CheckForIllegalCrossThreadCalls = false;
}

void timer1_Tick(object sender, EventArgs e)
{
textBox1.Text = int.Parse(textBox1.Text) + 1 + "";
richTextBox1.Text += DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "  " + textBox1.Text + "/r/n";
}

private void button1_Click(object sender, EventArgs e)
{
Thread.Sleep(10000);
}
}
}


在TextBox运行到3时点击“Stop”按钮,运行结果如下图:



通过这个实验可知,线程的占用会影响到System.Windows.Forms.Timer的触发时间和触发次数。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: