I have created a Service which runs on a Client. This Service inserts a Log Entry in a Database on Server. The Log entry is inserted via API which is running on Server. Below is the simplified code inside Service1
class. The Service is Timer based and runs repeatedly when needed. Hence, it needs to insert the Log Entry when needed. i.e. SendToServer()
function is executed repeatedly. I have remove the Timer code because it is not relevant here.
public class Logs
{
public string param1 { get; set; }
public string param2 { get; set; }
}
static HttpClient client = new HttpClient();
System.Timers.Timer timer = new System.Timers.Timer(); //New Edit
protected override void OnStart(string[] args)
{
SendToServer();
timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);//New Edit
timer.Interval = 60000; //New Edit
timer.Enabled = true; //NewEdit
}
private void OnElapsedTime(object source, ElapsedEventArgs e)//New Edit
{
SendToServer();
}
public void SendToServer()
{
RunAsync().GetAwaiter().GetResult();
}
static async Task RunAsync(EventLogEntry Log)
{
client.BaseAddress = new Uri("https://<IP>:<Port>/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
Logs log = new Logs
{
param1 = "value1";
param2 = "value2";
};
var url = await CreateLogsAsync(log);
}
static async Task<Uri> CreateLogsAsync(Logs log)
{
ServicePointManager.ServerCertificateValidationCallback = delegate (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
};
HttpResponseMessage response = await client.PostAsync("api/Logs", new StringContent(new JavaScriptSerializer().Serialize(log), Encoding.UTF8, "application/json"));
response.EnsureSuccessStatusCode();
return response.Headers.Location;
}
When I install the service or power up the Client Machine. The first database insert works fine. However, the data is not inserted in the database the second time. When I restart the system it again inserts the first log. I sense that there is problem with ASync Functions and the first call to API never returns correctly after inserting the data.
The similar code works perfectly in Console Application.