110,538
社区成员
发帖
与我相关
我的任务
分享
System.DateTime oldtime=new DateTime();
delegate void SetTextCallback(string strTime);//定义托管函数
System.Timers.Timer t = new System.Timers.Timer(100);//实例化Timer类
bool closeFlag;
public Form1()
{
InitializeComponent();
}
private void timeClass_Click(object sender, EventArgs e)
{
t.Elapsed+= new System.Timers.ElapsedEventHandler(theout);//到达时间的时候执行事件;
t.AutoReset = true;//设置是执行一次(false)还是一直执行(true);
t.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件;
}
public void theout(object source, System.Timers.ElapsedEventArgs e) //定时器调用
{
System.DateTime currentTime = new DateTime();
currentTime = DateTime.Now;
string ss = (currentTime - oldtime).TotalMilliseconds.ToString();
oldtime = currentTime;
AddText(ss);
}
void AddText(string strTime)
{
//在此处使用过:this.isDisposed和this.Disposing进行判定,无法解决
if (this.listView1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(AddText);
this.Invoke(d, new object[] { strTime });//此处出现,无法释放问题
}
else
{
string[] str = { listView1.Items.Count.ToString(), "测试", strTime };
ListViewItem item = new ListViewItem(str);
listView1.Items.Add(item);
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
t.Close();//这个地方如果增加一个关闭t.close的话也不行,定时器整个form关闭前没有被关闭!
Thread.Sleep(500);
}
,
while (true)
{
s++;
System.DateTime currentTime = new DateTime();
currentTime = DateTime.Now;
string ss = (currentTime - oldtime).TotalMilliseconds.ToString();
oldtime = currentTime;
if (this.InvokeRequired)
{
SetTextCallback d =AddText;//这个地方直接赋值,不用new,也就不产生递归了 object kkk = this.BeginInvoke(d, new object[] { ss.ToString() }); ;
}
Thread.Sleep((int)ms);
}
public void theout(object source, System.Timers.ElapsedEventArgs e)
{
System.DateTime currentTime = new DateTime();
currentTime = DateTime.Now;
string ss = (currentTime - oldtime).TotalMilliseconds.ToString();
oldtime = currentTime;
if (this.listView1.InvokeRequired)//这个地方从AddText函数中移出来了
{
SetTextCallback d = new SetTextCallback(AddText);
this.Invoke(d, new object[] { ss });//此处出现,无法释放问题
}
else
{
AddText(ss);
}
}
bool AddText(string strTime)
{
string[] str = { listView1.Items.Count.ToString(), "测试", strTime };
ListViewItem item = new ListViewItem(str);
listView1.Items.Add(item);
item.EnsureVisible();//设置当前记录可见
return true;
}