设置DateTimePicker仅在从定时操作触发时关闭应用程序

时间:2011-12-17 13:33:48

标签: c# datetimepicker timed-events

我在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# execute action after X seconds

2 个答案:

答案 0 :(得分:0)

控件不是线程安全的,这意味着您不能从另一个线程调用控件的方法。您可以等到控件的线程准备好使用Control.Invoke处理您的操作:

private void DBIO_Morning()
{
    DateTime date_current = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, 0, 0, 0);
    Action setValue = () => DTPicker_start.Value = date_current;
    if (DTPicker_start.InvokeRequired)
        DTPicker_start.Invoke(setValue);
    else
        setValue();
}

答案 1 :(得分:0)

您正在尝试修改At.Do()隐式创建的另一个线程中的GUI元素。请参阅this thread

System.Windows.Forms.Timer而不是At.Do()中使用System.Threading.Timer可能会解决问题。 (只需将new Timer(...)更改为new System.Windows.Forms.Timer(...)。)