您希望使用表单的Text 属性在表单的标题栏中显示当前日期和时间。这需要在后台任务上运行一个循环,以防止延迟阻塞您的 UI 表单并使其无响应。在循环内:
在主窗口关闭时处理您的 Task 也很重要,以避免在应用程序关闭时抛出异常。
最小的例子
public partial class MainForm : Form
{
public MainForm() => InitializeComponent();
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
_updaterTask = execDateTimeUpdater(_updaterTaskCTS.Token);
Disposed += (sender, e) => _updaterTaskCTS.Cancel();
}
private Task? _updaterTask;
private CancellationTokenSource _updaterTaskCTS = new CancellationTokenSource();
private async Task execDateTimeUpdater(CancellationToken token)
{
await Task.Run(async () =>
{
bool isDelay = false;
while(!token.IsCancellationRequested)
{
try
{
if (isDelay) await Task.Delay(TimeSpan.FromSeconds(1), token);
else BeginInvoke(() =>
{
var now = DateTime.Now;
Text = $"Main Form - {now.ToShortDateString()} {now.ToLongTimeString()}";
});
isDelay = !isDelay;
}
catch (OperationCanceledException)
{ }
}
});
}
}