I am using a WebApi delegating handler to forward requests to another server.
protected override async System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
string requestContent = string.Empty;
UriBuilder forwardUri = new UriBuilder(request.RequestUri);
//remove the proxy port and replace with an Http port
forwardUri.Port = 1900;
//send it on to the requested URL
request.RequestUri = forwardUri.Uri;
HttpClient client = new HttpClient();
if (request.Method == HttpMethod.Get)
{
request.Content = null;
}
try
{
var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
if (response.IsSuccessStatusCode)
{
ManageOnlineRequests(response);
}
return response;
}
catch (Exception ex)
{
return ManageOfflineRequests(request);
}
}
Everything works fine, but I am pseudo caching some data on the ManageOnlineRequests
. For that purpose I am using a single instance class that contains a representation of the models I want to keep, so that I can mock the response and return those when in offline mode ManageOfflineRequests
.
The question I have is : Since this is a Async method that contains a await
inside, is there any potential issues accessing the lists I have inside singleton class called by the ManageOnlineRequests
and ManageofflineRequests
?
Thanks
As Yuval said, this is unrelated to async-await
. If you plan on using these lists concurrently you need to make sure they are thread-safe.
Now, the simplest option is to use a lock
, however if you are using List<T>
specifically it's guaranteed to be thread-safe as long as you are only reading from it and not updating it concurrently:
It is safe to perform multiple read operations on a List, but issues can occur if the collection is modified while it’s being read
From List Class
A better solution would be to use the ImmutableList<T>
out of Microsoft.Bcl.Immutable
which is guaranteed to be thread-safe since it's immutable.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments