设置 DateTimePicker 仅在定时操作触发时关闭应用程序
我在 C# 中有一个函数,它首先将 GUI DateTimePicker 对象的值设置为今天的日期(时间 = 午夜),然后执行其他操作。当通过 GUI 按钮执行时,函数 (DBIO_Morning) 运行良好。但是,通过定时操作执行:
private void SetupTimedActions()
{
...
DateTime ref_morning = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, 8, 16, 0);
if (DateTime.Now < ref_morning)
At.Do(() => DBIO_Morning(), ref_morning);
...
}
它在第二行失败:(
private void DBIO_Morning()
{
DateTime date_current = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, 0, 0, 0);
DTPicker_start.Value = date_current;
...
}
At.Do 对象来自此处的第三个答案: C# 在 X 秒后执行操作 )
I have a function in C# which, at the outset, sets the value of a GUI DateTimePicker object to today's date (time = midnight), then does other stuff. When executed via GUI button, the function (DBIO_Morning) runs fine. But, executed via timed action:
private void SetupTimedActions()
{
...
DateTime ref_morning = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, 8, 16, 0);
if (DateTime.Now < ref_morning)
At.Do(() => DBIO_Morning(), ref_morning);
...
}
it fails in the second line:
private void DBIO_Morning()
{
DateTime date_current = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, 0, 0, 0);
DTPicker_start.Value = date_current;
...
}
( At.Do object is from the third answer here: C# execute action after X seconds )
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
控件不是线程安全的,这意味着您不能从另一个线程调用控件的方法。您可以等待,直到控件的线程准备好使用
Control.Invoke
处理您的操作:Controls are not thread-safe, meaning you must not call a control's methods from another thread. You can wait until the control's thread is ready to handle your action using
Control.Invoke
:您正尝试从另一个线程修改由
At.Do()
隐式创建的 GUI 元素。请参阅此主题。在
At.Do()
中使用System.Windows.Forms.Timer
而不是System.Threading.Timer
可能会解决该问题。 (只需将new Timer(...)
更改为new System.Windows.Forms.Timer(...)
。)You are trying to modify GUI elements from another thread, created implicitly by
At.Do()
. See this thread.Using
System.Windows.Forms.Timer
inAt.Do()
instead ofSystem.Threading.Timer
will probably solve the problem. (Just changenew Timer(...)
tonew System.Windows.Forms.Timer(...)
.)