I have 1 static class and 1 field and 2 methods within it:
static class MyClass{
private static HttpClient client = new HttpClient();
private static string SendRequestToServer(int id)
{
Task<HttpResponseMessage> response = client.GetAsync("some string");
responseTask.ContinueWith(x => PrintResult(x));
return "some new value";
}
private static void Print(Task<HttpResponseMessage> task)
{
Task<string> r = task.Result.Content.ReadAsStringAsync();
r.ContinueWith(resultTask => Console.WriteLine("result is: " + resultTask.Result));
}
}
The question is, if many threads start using MyClass and its methods, would it cause some problems?
All the resources accessed through these methods need to be thread-safe. In your case, they are not. If you look at the HttpClient documentation, it states:
You’re calling an instance method (
client.GetAsync), which is not be guaranteed to be thread-safe, so that could potentially cause problems for you.To mitigate this, you could:
HttpClienton each call.client(e.g. using a lock).Also, I can’t tell you if
PrintResultwill be thread-safe, butConsole.WriteLineshould be thread-safe.