This is a Windows forms application.
this.Server.GetLogMessages()
will block if there are no messages to get, so I want this in a separate thread. I'm putting the messages into a ConcurrentStack
and then pulling them out on the main thread to output them.
Here is the respective code:
private async Task UpdateLogs()
{
var logMessages = new ConcurrentStack<string>();
// assign to `_` to avoid warning
var _ = Task.Run(async () =>
{
await foreach (var message in this.Server.GetLogMessages())
{
logMessages.Push(message);
}
}, this.CancellationTokenSource.Token);
await foreach (var message in GetMessages())
{
// don't update the UI if task is canceled
if (this.CancellationTokenSource.Token.IsCancellationRequested)
{
break;
}
this.textLogs.AppendText($"{message}{Environment.NewLine}");
}
async IAsyncEnumerable<string> GetMessages()
{
var message = String.Empty;
while (!this.CancellationTokenSource.IsCancellationRequested)
{
while (!logMessages.TryPop(out message))
{
await Task.Delay(100);
}
yield return message;
}
}
}
It works fine, but seems as if it could be better/cleaner somehow.