Reputation:
So I want to keep a list in memory, with a get and post method.
All users must be able to post and read from the same list. I've looked into
HttpContext.Current.Session
for a controller, but it only keeps the same list in memory for a single user.
So how can I implement a List which is accessible by all users?
My project is WebAPI, so it must be easily accesible by Rest.
Upvotes: 2
Views: 2722
Reputation: 33149
As Darin pointed out, you can use HttpContext.Current.Application
to store values that must be available to all application instances on the server. You must be sure, though, to do any updates in a thread-safe manner so that multiple instances (i.e., request handlers) cannot update the same value simultaneously.
If you are running your application on a Web farm, so with multiple Web servers to handle more users, this is not a good option because Application
state is local on each server. In that case it would be better to either store the shared state in a database or in a distributed cache such as Redis (see https://learn.microsoft.com/en-us/aspnet/core/performance/caching/distributed).
Upvotes: 0
Reputation: 1039508
You could use the HttpContext.Current.Application
instead which will be shared between all your users:
HttpContext.Current.Application["someList"] = new List<string> { "a", "b" };
and then retrieve like this:
var myList = HttpContext.Current.Application["someList"] as List<string>;
As an alternative you could just use a static property:
public static class MyHelper
{
static MyHelper()
{
MyList = new List<string>();
}
public static IList<string> MyList { get; set; }
}
and then you could use like this:
MyHelper.MyList = new List<string> { "a", "b" };
and to retrieve the value:
IList<string> myList = MyHelper.MyList;
This being said, be aware that if you are running in a web farm you might need to consider some distributed caching because HttpContext.Current.Application
will be stored in-memory of the current web node.
Another important remark about this is that the List<T>
class is not thread-safe so sharing a single instance between different threads could cause data corruption unless you properly synchronize the access to this list between the readers and writers by using the corresponding locking mechanisms or use ConcurrentBag<T>
instead which is designed to be thread-safe.
Upvotes: 4