Question

Is the RestClient class in the API thread safe?

  • 10 August 2021
  • 3 replies
  • 885 views

As the title asks. Let's say I have the below code, where three tasks are being run concurrently. Let's also say that within each task, they are calling a single, shared RestClient instance and sending requests to the RingCentral API to gather various information.


Is this thread safe to have multiple threads making calls concurrently using the same RestClient instance? I have read that in a plain HttpClient instance, it would be thread safe if the requests were the 'async' version of those requests, ie, GetAsync(), PostAsync, etc. It's not immediately clear if the RingCentral API's RestClient class is working in that manner.


public async Task MainTask()
{
  Task[] tasks = new Task[3];
  tasks[0] = new Task(() => asyncMethod1());
  tasks[1] = new Task(() => asyncMethod2());
  tasks[2] = new Task(() => asyncMethod3());

  Task.WaitAll(tasks);
}
public async Task asyncMethod1()
{
  //do stuff using a shared RestClient instance
}
public async Task asyncMethod2()
{
  //do stuff using a shared RestClient instance
}
public async Task asyncMethod3()
{
  //do stuff using a shared RestClient instance
}






3 replies

Similar concern in this reference: https://community.ringcentral.com/questions/7550/java-sdk-restclient-thread-safe.html

@Phong Vu if you can clear the query here

I'd like an official answer, but I looked at the RestClient source code as posted on GitHub. I'm pretty new to multithreading, but just looking at it, my feeling is that it is not thread safe, and that multiple threads using the same RestClient instance would need to lock the RestClient instance to make it safe. Or, alternatively, use multiple separate RestClient instances, but I'm not sure how the RingCentral API would react to that.

I am the author of the RingCentral.Net SDK. Yes I think it is thread safe. Because the SDK does NOT explicitly use threads at all. It always use async/await. And there is no temporary variables shared between threads. (there are variables shared but you are not supposed to update them, such as the clientId, clientSecret, server).

> I have read that in a plain HttpClient instance, it would be thread safe if the requests were the 'async' version of those requests, ie, GetAsync(), PostAsync,

We are using the SendAsync() method: https://github.com/ringcentral/RingCentral.Net/blob/master/RingCentral.Net/RestClient.cs#L86




Reply