Good day. Tell me, please, how can I implement long pulling to VKontakte servers in C #? Now I use a recursive call to an asynchronous method, but this creates certain bugs in the application.

private async Task GetUpdatesFromServer() { await Task.Run(async () => { string url = $"какой-то урл"; using (var http = new HttpClient()) { var json = await http.GetStringAsync(url); var updates = JsonConvert.DeserializeObject<LongPollUpdates>(json); Ts = updates.Ts; if (updates.Updates.Count > 0) { await SendUpdate.Invoke(updates.Updates); } } await GetUpdatesFromServer(); }); } 
  • And why not replace the recursion with a while ? - VladD
  • in an endless loop to do? - Arthur
  • Well yes. And what kind of SendUpdate type? What does Invoke do? - VladD

1 answer 1

Here is a piece of code I once wrote:

  public async Task GetMessagesAsync() { lock(_login) if (_cts != null) return; _cts = new CancellationTokenSource(); LongPollServerResponse longPollingServer = null; try { longPollingServer = _myAcc.Messages.GetLongPollServer(true); } catch (NeedValidationException ex) { try { await RegistrationExplicityAsync(ex.redirectUri.ToString()).ConfigureAwait(false); longPollingServer = _myAcc.Messages.GetLongPollServer(true); } catch (Exception) { return; } } CancellationToken ct = _cts.Token; string ts; while (true) { try { var answer = await longPolling.GetStringAsync($"https://{longPollingServer.Server}?act=a_check&key={longPollingServer.Key}&ts={longPollingServer.Ts}&wait=100&version=1").ConfigureAwait(false); if (ct.IsCancellationRequested) return; JObject jAnswer = JObject.Parse(answer); try { ThrowIfFailed(jAnswer); } catch (VkLongPollingException ex) { if (ex.Error == 1) { ts = jAnswer.SelectToken("$.ts").ToString(); longPollingServer.Ts = ulong.Parse(ts); } else if (ex.Error == 2 || ex.Error == 3) longPollingServer = _myAcc.Messages.GetLongPollServer(true); else if (ex.Error == 4) { return; } continue; } ts = jAnswer.SelectToken("$.ts").ToString(); longPollingServer.Ts = ulong.Parse(ts); MessageHandler(jAnswer); } catch (Exception ex) { await Task.Delay(10 * 1000).ConfigureAwait(false); } } } 
  • Ehhh, where were you an hour ago? Already wrote it myself) Approximately the same, only used Task.ContinueWith (() => ...). In any case - thanks) - Arthur
  • Thank! But if you added a description of the class VkLongPollingException here, it would be even better. - Daniel Vygolov