Static method, static field and multitasking in C #

I have 1 static class and 1 field and 2 methods inside 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)); } } 
Question: if many threads start using MyClass and its methods, would they cause some problems?
+4
source share
2 answers

All resources available through these methods must be thread safe. In your case, this is not so. If you look at the HttpClient documentation, it says:

All public static (Shared in Visual Basic) members of this type are thread safe. Any instance members do not guarantee thread safety .

You call the instance method ( client.GetAsync ), which does not guarantee that it will be thread safe, which could potentially cause problems for you.

To reduce this, you can:

  • create a new (local) HttpClient for each call.
  • synchronize access to client (for example, by means of blocking).

In addition, I cannot say whether PrintResult be thread safe, but Console.WriteLine should be thread safe.

+3
source

You are likely to expect unpredictable results with this setting. It is necessary that threads access data in a synchronous manner. lock requires an instruction to use in your case to make sure that execution is synchronous and stable.

 private static Object locker= new Object(); private static string SendRequestToServer(int id) { lock(locker) { Task<HttpResponseMessage> response = client.GetAsync("some string"); responseTask.ContinueWith(x => PrintResult(x)); return "some new value"; } } 
+1
source

Source: https://habr.com/ru/post/1443821/


All Articles