Set HttpClient timeout to infinite

This commit is contained in:
Lucas Bortoli
2022-06-27 08:26:11 -03:00
parent caae5decb7
commit b66620c9da

View File

@@ -7,6 +7,7 @@ using System.Linq;
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Text; using System.Text;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Web; using System.Web;
@@ -28,46 +29,53 @@ namespace ntfysh_client
httpClient = new HttpClient(); httpClient = new HttpClient();
subscribedTopics = new Dictionary<string, StreamReader>(); subscribedTopics = new Dictionary<string, StreamReader>();
httpClient.Timeout = TimeSpan.FromMilliseconds(Timeout.Infinite);
ServicePointManager.DefaultConnectionLimit = 100; ServicePointManager.DefaultConnectionLimit = 100;
} }
public async Task SubscribeToTopic(string topicId) public async Task SubscribeToTopic(string topicId)
{ {
var stream = await httpClient.GetStreamAsync($"https://ntfy.sh/{HttpUtility.UrlEncode(topicId)}/json"); HttpRequestMessage msg = new HttpRequestMessage(HttpMethod.Get, $"https://ntfy.sh/{HttpUtility.UrlEncode(topicId)}/json");
using (var response = await httpClient.SendAsync(msg, HttpCompletionOption.ResponseHeadersRead))
using (StreamReader reader = new StreamReader(stream))
{ {
subscribedTopics.Add(topicId, reader); using (var body = await response.Content.ReadAsStreamAsync())
try
{ {
// The loop will be broken when this stream is closed using (StreamReader reader = new StreamReader(body))
while (true)
{ {
var line = await reader.ReadLineAsync(); subscribedTopics.Add(topicId, reader);
Debug.WriteLine(line); try
NtfyEventObject nev = JsonConvert.DeserializeObject<NtfyEventObject>(line);
if (nev.Event == "message")
{ {
if (OnNotificationReceive != null) // The loop will be broken when this stream is closed
while (true)
{ {
var evArgs = new NotificationReceiveEventArgs(nev.Title, nev.Message); var line = await reader.ReadLineAsync();
OnNotificationReceive(this, evArgs);
Debug.WriteLine(line);
NtfyEventObject nev = JsonConvert.DeserializeObject<NtfyEventObject>(line);
if (nev.Event == "message")
{
if (OnNotificationReceive != null)
{
var evArgs = new NotificationReceiveEventArgs(nev.Title, nev.Message);
OnNotificationReceive(this, evArgs);
}
}
} }
} }
} catch (Exception ex)
} catch(Exception ex) {
{ Debug.WriteLine(ex);
Debug.WriteLine(ex);
// If the topic is still registered, then that stream wasn't mean to be closed (maybe network failure?) // If the topic is still registered, then that stream wasn't mean to be closed (maybe network failure?)
// Restart it // Restart it
if (subscribedTopics.ContainsKey(topicId)) if (subscribedTopics.ContainsKey(topicId))
{ {
SubscribeToTopic(topicId); SubscribeToTopic(topicId);
}
}
} }
} }
} }