Configure await false for http client get async calls

master
Tudor Stanciu 2022-12-29 19:03:14 +02:00
parent eb68d31970
commit ac24e59e91
7 changed files with 47 additions and 29 deletions

View File

@ -1,10 +1,11 @@
using System.Threading.Tasks; using System.Threading;
using System.Threading.Tasks;
namespace GoDaddyDDNS.Abstractions namespace GoDaddyDDNS.Abstractions
{ {
public interface IDynamicDNSService public interface IDynamicDNSService
{ {
Task Initialize(); Task Initialize(CancellationToken cancellationToken);
Task Execute(); Task Execute(CancellationToken cancellationToken);
} }
} }

View File

@ -1,11 +1,12 @@
using GoDaddyDDNS.Models; using GoDaddyDDNS.Models;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace GoDaddyDDNS.Abstractions namespace GoDaddyDDNS.Abstractions
{ {
internal interface IGoDaddyConnector internal interface IGoDaddyConnector
{ {
Task<DNSRecord[]> GetRecords(); Task<DNSRecord[]> GetRecords(CancellationToken cancellationToken);
Task UpdateRecords(DNSRecord[] records); Task UpdateRecords(DNSRecord[] records, CancellationToken cancellationToken);
} }
} }

View File

@ -1,9 +1,10 @@
using System.Threading.Tasks; using System.Threading;
using System.Threading.Tasks;
namespace GoDaddyDDNS.Abstractions namespace GoDaddyDDNS.Abstractions
{ {
internal interface IPublicIPTracker internal interface IPublicIPTracker
{ {
Task<string> Get(); Task<string> Get(CancellationToken cancellationToken);
} }
} }

View File

@ -3,6 +3,7 @@ using GoDaddyDDNS.Models;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System; using System;
using System.Linq; using System.Linq;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace GoDaddyDDNS.Services namespace GoDaddyDDNS.Services
@ -23,19 +24,19 @@ namespace GoDaddyDDNS.Services
_goDaddyConnector=goDaddyConnector; _goDaddyConnector=goDaddyConnector;
} }
public async Task Initialize() public async Task Initialize(CancellationToken cancellationToken)
{ {
// check records // check records
var records = await _goDaddyConnector.GetRecords(); var records = await _goDaddyConnector.GetRecords(cancellationToken);
if (records == null || records.Length == 0) if (records == null || records.Length == 0)
throw new Exception("No valid record found."); throw new Exception("No valid record found.");
DNSRecords = records; DNSRecords = records;
PublicIP = records.First().Data; PublicIP = records.First().Data;
} }
public async Task Execute() public async Task Execute(CancellationToken cancellationToken)
{ {
var publicIP = await _publicIPTracker.Get(); var publicIP = await _publicIPTracker.Get(cancellationToken);
if (PublicIP != publicIP) if (PublicIP != publicIP)
{ {
_logger.LogWarning($"[{DateTime.Now}]: Public IP has changed from '{PublicIP}' to '{publicIP}'"); _logger.LogWarning($"[{DateTime.Now}]: Public IP has changed from '{PublicIP}' to '{publicIP}'");
@ -45,7 +46,7 @@ namespace GoDaddyDDNS.Services
return record; return record;
}).ToArray(); }).ToArray();
await _goDaddyConnector.UpdateRecords(newRecords); await _goDaddyConnector.UpdateRecords(newRecords, cancellationToken);
PublicIP = publicIP; PublicIP = publicIP;
DNSRecords = newRecords; DNSRecords = newRecords;

View File

@ -10,6 +10,7 @@ using System.Linq;
using System.Net.Http; using System.Net.Http;
using System.Net.Http.Headers; using System.Net.Http.Headers;
using System.Text; using System.Text;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace GoDaddyDDNS.Services namespace GoDaddyDDNS.Services
@ -43,12 +44,12 @@ namespace GoDaddyDDNS.Services
private string GetRecordRoute(string name) => _recordRoute.Replace("{domain}", _domain).Replace("{type}", _recordType).Replace("{name}", name); private string GetRecordRoute(string name) => _recordRoute.Replace("{domain}", _domain).Replace("{type}", _recordType).Replace("{name}", name);
public async Task<DNSRecord[]> GetRecords() public async Task<DNSRecord[]> GetRecords(CancellationToken cancellationToken)
{ {
var list = new List<DNSRecord>(); var list = new List<DNSRecord>();
foreach (var name in _records) foreach (var name in _records)
{ {
var dnsRecord = await GetRecord(name); var dnsRecord = await GetRecord(name, cancellationToken);
if (dnsRecord == null) if (dnsRecord == null)
_logger.LogWarning($"The record '{name}' was not found and will be ignored."); _logger.LogWarning($"The record '{name}' was not found and will be ignored.");
else else
@ -57,12 +58,12 @@ namespace GoDaddyDDNS.Services
return list.ToArray(); return list.ToArray();
} }
private async Task<DNSRecord> GetRecord(string name) private async Task<DNSRecord> GetRecord(string name, CancellationToken cancellationToken)
{ {
var route = GetRecordRoute(name); var route = GetRecordRoute(name);
using (var response = await _httpClient.GetAsync(route)) using (var response = await _httpClient.GetAsync(route, cancellationToken).ConfigureAwait(false))
{ {
var resultAsString = await response.Content.ReadAsStringAsync(); var resultAsString = await response.Content.ReadAsStringAsync(cancellationToken);
if (response.IsSuccessStatusCode) if (response.IsSuccessStatusCode)
{ {
var result = JsonConvert.DeserializeObject<DNSRecord[]>(resultAsString); var result = JsonConvert.DeserializeObject<DNSRecord[]>(resultAsString);
@ -79,13 +80,13 @@ namespace GoDaddyDDNS.Services
} }
} }
public async Task UpdateRecords(DNSRecord[] records) public async Task UpdateRecords(DNSRecord[] records, CancellationToken cancellationToken)
{ {
foreach (var record in records) foreach (var record in records)
await UpdateRecord(record); await UpdateRecord(record, cancellationToken);
} }
private async Task UpdateRecord(DNSRecord record) private async Task UpdateRecord(DNSRecord record, CancellationToken cancellationToken)
{ {
var route = GetRecordRoute(record.Name); var route = GetRecordRoute(record.Name);
var data = JsonConvert.SerializeObject(new DNSRecord[] { record }, new JsonSerializerSettings var data = JsonConvert.SerializeObject(new DNSRecord[] { record }, new JsonSerializerSettings
@ -95,12 +96,12 @@ namespace GoDaddyDDNS.Services
var content = new StringContent(data, Encoding.UTF8, "application/json"); var content = new StringContent(data, Encoding.UTF8, "application/json");
using (var response = await _httpClient.PutAsync(route, content)) using (var response = await _httpClient.PutAsync(route, content, cancellationToken))
{ {
if (response.IsSuccessStatusCode) if (response.IsSuccessStatusCode)
return; return;
var resultAsString = await response.Content.ReadAsStringAsync(); var resultAsString = await response.Content.ReadAsStringAsync(cancellationToken);
var error = JsonConvert.DeserializeObject<ErrorBody>(resultAsString); var error = JsonConvert.DeserializeObject<ErrorBody>(resultAsString);
throw new Exception($"{error.Code}: {error.Message}"); throw new Exception($"{error.Code}: {error.Message}");
}; };

View File

@ -4,6 +4,7 @@ using Microsoft.Extensions.Logging;
using System; using System;
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace GoDaddyDDNS.Services namespace GoDaddyDDNS.Services
@ -21,14 +22,14 @@ namespace GoDaddyDDNS.Services
_publicIPProviders = configuration.GetSection("PublicIPProviders").Get<string[]>(); _publicIPProviders = configuration.GetSection("PublicIPProviders").Get<string[]>();
} }
public async Task<string> Get() public async Task<string> Get(CancellationToken cancellationToken)
{ {
if (_publicIPProviders == null || _publicIPProviders.Length == 0) if (_publicIPProviders == null || _publicIPProviders.Length == 0)
throw new Exception("No public IP provider is configured."); throw new Exception("No public IP provider is configured.");
foreach (var provider in _publicIPProviders) foreach (var provider in _publicIPProviders)
{ {
var ip = await GetIP(provider); var ip = await GetIP(provider, cancellationToken);
if (ip != null) if (ip != null)
return ip; return ip;
} }
@ -36,13 +37,13 @@ namespace GoDaddyDDNS.Services
throw new Exception("The public IP could not be obtained from any of the configured providers."); throw new Exception("The public IP could not be obtained from any of the configured providers.");
} }
private async Task<string> GetIP(string providerUrl) private async Task<string> GetIP(string providerUrl, CancellationToken cancellationToken)
{ {
string ip = null; string ip = null;
using (var response = await _httpClient.GetAsync(providerUrl)) using (var response = await _httpClient.GetAsync(providerUrl, cancellationToken).ConfigureAwait(false))
{ {
if (response.IsSuccessStatusCode) if (response.IsSuccessStatusCode)
ip = await response.Content.ReadAsStringAsync(); ip = await response.Content.ReadAsStringAsync(cancellationToken);
else else
return null; return null;
} }

View File

@ -29,15 +29,27 @@ namespace GoDaddyDDNS
while (!stoppingToken.IsCancellationRequested) while (!stoppingToken.IsCancellationRequested)
{ {
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now); _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
await _dynamicDNSService.Execute(); await Execute(stoppingToken);
await Task.Delay(_delay, stoppingToken); await Task.Delay(_delay, stoppingToken);
} }
} }
private async Task Execute(CancellationToken cancellationToken)
{
try
{
await _dynamicDNSService.Execute(cancellationToken);
}
catch (Exception e)
{
_logger.LogError(e, "An unexpected error was encountered during execution.");
}
}
public override async Task StartAsync(CancellationToken cancellationToken) public override async Task StartAsync(CancellationToken cancellationToken)
{ {
_logger.LogInformation("Starting worker..."); _logger.LogInformation("Starting worker...");
await _dynamicDNSService.Initialize(); await _dynamicDNSService.Initialize(cancellationToken);
await base.StartAsync(cancellationToken); await base.StartAsync(cancellationToken);
} }