C
C#9mo ago
Kohai

❔ Asynchronously events handling flow

Hi, I am writing a bot and I don't know how to organize events handling with tasks. I have class that implements these methods:
Task StartPolling();
Task HandleUpdateAsync(GroupUpdate update);
Task StartPolling();
Task HandleUpdateAsync(GroupUpdate update);
The actions flow is follow: StartPolling() listens to a server for events. When the events are received, it should run task that creates kind of threads to handle each event by calling HandleUpdateAsync(GroupUpdate update) and keep listening to the server. So the question is how to do that? My version is follow but I guess it blocks current thread until the lambda function is not over because of await word before Task.Run(). When I remove await, Rider warns me to put that word.
await Task.Run(async () =>
{
foreach (var update in updates.Updates)
await HandleUpdateAsync(update);
});
await Task.Run(async () =>
{
foreach (var update in updates.Updates)
await HandleUpdateAsync(update);
});
the whole code:
public async Task StartPolling()
{
Console.WriteLine("Polling...");
try
{
while (true)
{
var longPollResponse = await _botApi.Groups.GetLongPollServerAsync(_groupId);
var updates = await _botApi.Groups.GetBotsLongPollHistoryAsync(new BotsLongPollHistoryParams
{
Ts = longPollResponse.Ts,
Key = longPollResponse.Key,
Server = longPollResponse.Server,
Wait = 25
});

if (updates.Updates is null) continue;
if (updates.Updates.Count < 1) continue;
await Task.Run(async () =>
{
foreach (var update in updates.Updates)
await HandleUpdateAsync(update);
});
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
public async Task StartPolling()
{
Console.WriteLine("Polling...");
try
{
while (true)
{
var longPollResponse = await _botApi.Groups.GetLongPollServerAsync(_groupId);
var updates = await _botApi.Groups.GetBotsLongPollHistoryAsync(new BotsLongPollHistoryParams
{
Ts = longPollResponse.Ts,
Key = longPollResponse.Key,
Server = longPollResponse.Server,
Wait = 25
});

if (updates.Updates is null) continue;
if (updates.Updates.Count < 1) continue;
await Task.Run(async () =>
{
foreach (var update in updates.Updates)
await HandleUpdateAsync(update);
});
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
1 Reply
Accord
Accord9mo ago
Looks like nothing has happened here. I will mark this as stale and this post will be archived until there is new activity.