作者testSV (喔喔喔喔喔)
看板C_Sharp
标题Re: [问题] 回圈暂停并更新控制项
时间Sun Feb 1 15:40:49 2015
工作要开在别的Thread里面
为确保Thread在程式结束後会消失 偷懒的话设IsBackground=true
要不然得另外弄flag来同步 e.g. while(IsRunning){....}
另外要注意一点
如果要存取DependencyObject的成员
必须要在同个Thread内呼叫
否则会出现"
呼叫执行绪无法存取此物件,因为此物件属於另一个执行绪。"的错误
所以必须透过Dispatcher.Invoke来存取
下面的例子
就是会开个Thread 每隔一秒钟後会更改Title
因为偷懒 所以直接用匿名delegate做掉
private void Button_Click(object sender, RoutedEventArgs e)
{
System.Threading.Thread thread = new System.Threading.Thread(
delegate()
{
Int16 i=0;
//做某些事情
while (i<10)
{
System.Threading.Thread.Sleep(1000);
i++;
//直接存取会出错
//this.Title = i.ToString();
this.Dispatcher.Invoke(
new Action(
delegate()
{
this.Title = i.ToString();
}
)
);
}
}
);
thread.Start();
}
另外针对你的应用
可以用System.Windows.Threading.DispatcherTimer比较快
System.Windows.Threading.DispatcherTimer timer =
new System.Windows.Threading.DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(1);
timer.Tick +=
delegate(object oo, EventArgs ee)
{
i++;
this.Title = i.ToString();
};
timer.Start();
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 114.46.79.242
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/C_Sharp/M.1422776451.A.210.html
※ 编辑: testSV (114.46.79.242), 02/01/2015 15:48:29