I am writing a C# library (.NET 4.6.1) that will use Tasks to be able to run several snippets of code in the background. This library will be called by a Powershell script that is triggered from a TaskScheduler item
When I do testing by launching Powershell, and then calling the library, all is working correctly. However, through the TaskScheduler it does not work, and I can replicate this behavior issue with a console application.
Main library thread:
public class MainLibrary {
private static HttpClient g_httpclient_Main = new HttpClient();
private static List<Task> g_list_Tasks = new List<Task>();
public void EntryPoint() {
SetupTasks();
foreach (Task _t_List in g_list_Tasks)
{
_t_List.Start();
}
Task.WaitAll(g_list_Tasks.ToArray());
}
}
Each of the tasks were created before the foreach loop in a separate function/method of the MainLibrary class like this:
private void SetupTasks() {
Task _task_TollGate = new Task(() =>
{
QueueEndpointCall();
});
g_list_Tasks.Add(_task_TollGate);
}
private async Task QueueEndpointCall()
{
try {
HttpResponseMessage _httprm = await g_httpclient_Main.GetAsync("http://www.google.com");
_string_HTTP = await _httprm.Content.ReadAsStringAsync();
....other code
}
catch (Exception e) {
File.WriteLine...
}
}
When I run the console application and put a breakpoint, when the GetAsync is hit and run, it will jump back to the main thread which if I understand correctly is fine/correct. Then hitting the Task.WaitAll line, seemingly the background Task has finished, but the placeholder I have in the snippet "...other code" does not execute. Launching Powershell manually, and calling the library, works fine.
Any suggestions here ? I am considering upgrading to .NET v8.0, however I don't have the resources at this moment to do that and would like to get this working in .NET 4.6.1
Edit (7-Jan-2025) - I migrated to .NET 8 with no success, and even tried the suggestion to locally declare HttpClient although I wouldn't think that's the problem, and still the "...other code" is not being executed. I believe an error is being swallowed as I don't see an error log file from the try/catch that is wrapping the HttpClient call.
Thanks.
static List<Task>looks really scary to me, threaded and async code tend to be much simpler and safer when everything is immutable and pure, i.e. no side effects, only parameters and return values. And if this is a library I would recommend targeting .net standard, that way it is usable in both .net 4.x and 5+._t_Listand_task_TollGatare local variables, and should not be prefixed with underscore. See C# identifier naming rules and conventions.