My try to simplify and prettify the method.
Avoid using globals in async code, pass Token as argument.
// optimized out async State Machine
private Task UpdateLogsAsync(IProgress<string> status, CancellationToken token) => Task.Run(async () =>
{
await foreach (var message in this.Server.GetLogMessages().WithCancellation(token))
{
token.ThrowIfCancellationRequested();
status.Report(message);
}
}, token);
Usage
// synchronized callback. Create new in UI Thread and its body will be always executed there.
IProgress<string> status = new Progess<string>(message =>
{
this.textLogs.AppendText($"{message}{Environment.NewLine}");
});
try
{
await UpdateLogsAsync(status, this.CancellationTokenSource.Token);
}
catch (OperationCanceledException ex)
{
status.Report(ex.Message);
}