【发布时间】:2014-03-13 20:05:15
【问题描述】:
我有一个 UI 应用程序,它每秒记录一些内容。每次OpenFileHandler 被触发时,我都必须开始记录到一个新文件。这是代码的一个非常简化的版本:
string _logItem;
string _fileName;
CancellationTokenSource _cts;
Task _task;
private void OpenFileHandler(object sender, EventArgs e)
{
// once OpenFileHandler has been fired,
// the _logItem should go to the new file
if (_task != null && !_task.IsCompleted)
{
_cts.Cancel();
// can't do: _task.Wait();
}
if ( _fileName != null )
{
_cts = new CancellationTokenSource();
_task = LogAsync(_fileName, _cts.Token);
}
}
private async Task LogAsync(string fileName, CancellationToken ct)
{
using (var writer = new System.IO.StreamWriter(fileName, false))
{
try
{
while (true)
{
await Task.Delay(1000, ct);
await writer.WriteLineAsync(_logItem);
}
}
finally
{
writer.WriteLine("end of log!");
}
}
}
问题:OpenFileHandler 是同步的,但我需要确保待处理的WriteLineAsync 已完成并且旧日志文件已关闭,然后才能开始新的LogAsync 任务。
我不能在OpenFileHandler 内执行_task.Wait(),因为它会阻塞 UI 线程。
我也无法将OpenFileHandler 设为async 方法并在其中执行await _task。这是因为当应用程序关闭时,OpenFileHandler 被触发,_fileName 是 null,我希望 "end of log!" 行仍然存在于日志中。
我该如何解决这个问题?
【问题讨论】:
标签: c# .net events asynchronous async-await