日期:2014-05-18 浏览次数:21055 次
private void form_Load()
{
Action loopAction = MyMethod;
loopAction.BeginInvoke(null,null);
}
private void MyMethod()
{
while(true)
{
//DoSomething
Thread.Sleep(100);
}
}
------解决方案--------------------
使用timer
private System.Threading.Timer _timer = null;//这个要使用个全局变量,代码不好看
private void StartMyWork()
{
_timer = new Timer(MyMethod, null, 0, 100);
}
private void MyMethod(object obj)
{
/*DoSomething*/
//如果在timer里面需要更新UI控件的话,由于这个timer不是在主线程中执行的因此要这样访问:
this.Dispatcher.BeginInvoke(
new Action(
() =>
{
//这样更新UI
}));
}
------解决方案--------------------
期待问题的解答,可以用一下委托不
------解决方案--------------------
我猜想你肯定是碰到了MessageBox.Show("maopian jijiang kaishi");在异步线程中会出异常的问题。给你个完整的吧
private void Form1_Load(object sender, EventArgs e)
{
Run();
}
#region 每隔一段特定的时间执行一次:程序启动后在每隔10秒之后再次执行
private System.Threading.Timer tt = null;
public void Run()
{
if (tt == null)
{
tt = new System.Threading.Timer(executeRun, null, 5000, 10000);
}
}
public void executeRun(object obj)
{
this.BeginInvoke(new Action(() => { MessageBox.Show("maopian yijing bofang le" + DateTime.Now.ToString()); }));
//timer1.Start();
}
#endregion
------解决方案--------------------
另一个版本,使用while...Sleep的方式
private void Form1_Load(object sender, EventArgs e)
{
Action action = Run;
action.BeginInvoke(null, null);
}
#region 每隔一段特定的时间执行一次:程序启动后在每隔10秒之后再次执行
public void Run()
{
while (true)
{
executeRun();
Thread.Sleep(1000);
}
}
public void executeRun()
{
this.BeginInvoke(new Action(() => { MessageBox.Show("maopian yijing bofang le" + DateTime.Now.ToString()); }));
}
#endregion
------解决方案--------------------
只要你是在this.BeginInvoke(new Action(() => {/*Dosomething*/ }));Dosomething那里更新主界面或者打开窗口的话,都没有问题的,不需再调用你以前的timer了喔,要不然就会有两个timer,所表达的意思就和你的本意完全不一样了。