In MVC if I want to lock a method so that it will never run more than once at a time (despite multiple users using the application), I can just use a static object:
private static Object lock= new Object();
But in my case I want to create a lock with a name, so the application will only lock for those users trying to use the same name.
Normally in C# I would use a Mutex(name) for this, but is there an appropriate equivalent in server world? (it needs to be global for all users)
Edit:
This is a client application, rather than a public site - so there would only ever be max say, 20 users accessing the application at a time.
You do not want to block anything on server side, what you want is to not execute anything on server side once condition is met. It can be handled in number of ways: Error page redirection, Notification to the client about critical condition met...etc
In other words, for selected users, handle that special condition, but
do not block anything.
Related
I am trying to have a variable that is an object exist once on the server for an ASP.Net Application.
I want to fire it up and then allow every user of the application to have it.
My understanding is that the Global.asax file contains a method called Application_Start that starts up every time a user calls for the first time. And it has a method Application_BeginRequest for each request.
The method Application_Start does not suit my needs as it is once per user.
Is it possible to somehow have an object for all users?
Storing a global variable in a static class will not work either as it once instance per user of the application.
The reason for the need is we are trying to use a new product and improve performance(speed) and the declaration and initialization of this object is a performance cost we are trying to circumvent.
Stackoverflow-Global.asax does not really help me and
Stackoverflow-SessionVariables does not solve my need
Is there a way of storing an object variable in a file available for the whole pool of users? I am at a a loss as tho the solution?
You can use Cache to cache you application data machine wide.
I currently am using a ConcurrentDictionary to hold a collection of login names that have authenticated with my API. I do this to prevent duplicate logins from other web clients (a requirement of the system architecture). If a user authenticates with a login that is already "logged in" they are given a choice ...
Continue and the previous login will be expired
Cancel and the current session will be logged out
I am using a ConcurrentDictionary because it is supposed to be thread safe which is important in an environment where multiple clients are accessing the API.
What I am asking is if the ConcurrentDictionary is needed because I am running into trouble deleting all items in the collection that match a given key. Is a ConcurrentDictionary called for in this case? If not, would a plain Dictionary suffice? If not, and a ConcurrentDictionary is needed is there a method that will remove all entries matching a given key? All I can see is TryRemove() which only seems to remove a single entry.
The direct answer to your question:
Yes, you need a ConcurrentDictionary. You are sharing state across several threads.
Remember, a dictionary has one entry per key. That's the definition of what a Dictionary is, and a ConcurrentDictionary doesn't change that.
A fuller and more complete answer to your requirement is below.
The whole solution is short sighted as you have no connection with the session infrastructure to know when a user's session has timed out and effectively caused them to be logged out. Additionally there is no coordination with other instances of your app if you ever think about deploying to a cloud platform that spins up new instances.
In other words, you are putting yourself in a situation that makes it very difficult to scale your app without breaking this feature.
Probably one of the most robust ways of handling the single session requirement is to use your database:
Have a field that keeps track of the last session ID your user had when logging in.
Add a session listener to clear the field when the session times out
If the session ID is not the same as what's in the field, you know you have a new login attempt.
If you need complete control over the session ID, then supply your own session id manager (may be necessary to include an encoded server ID in it).
You'll find that the requirement is much more involved than it sounds on the surface. You can't think like a desktop application in the web space--which is precisely where this requirement even comes from.
I am currently converting a Windows Phone 7 application to its web counterpart. The application uses a big main thread from which the data is gathered, and for the moment I have just copied and pasted it as is (just a standard thread operation), in my ASP.NET MVC controller.
Sync _Sync = new Sync();
_Sync.StartSync();
The tasks work OK, but because the thread makes use of global data set from the cookies, issues arise when accessing the page with 2 different usernames. For example, if I login with "user1" in Firefox and then try to login in Chrome with another user (say "user2"), then it will automatically change the async data gathered for the first user; meaning that I will always see data pulled out from the last user logged in (regardless of the fact that I was just logged in in Firefox with another user, initially), and not each others' separate data.
In other words, the thread doesn't start separately for each individual user. How could I fix this behavior?
Static fields and properties are shared across threads and should generally not be used to store data that pertains to a specific user or web request.
One of the following suggestions should fix your threading issues and keep your user data separate.
Create an instance of the Sync class for each request and remove any static fields / properties from the class.
Add a method to the Sync class that returns an instance of the data for a specific user instead of storing the data in static fields / properties.
Quick question: Is there a "per-user" data storage object (similar to Session) that I can store data in the global scope (similar to HttpRuntime.Cache)? Almost as if Session and HttpRuntime.Cache had a baby.
Full Background: I have a ASP.NET website that was originally written for a single thread. Now I changed it so that certain actions will spawn a background thread and the browser polls a service to get status updates.
The problem I am having with this is that certain pieces of data are stored into the HttpContext.Session[] object (membership authentication token, for example). These pieces of data need to be unique to each user and accessible to the background thread. Session is not available to the background thread.
I am aware of HttpRuntime.Cache but that would require micromanagement to segment out the users and to expire it at the same time the session is expired. Session, on the other hand, automatically expires this things at the right times that I want it too and is already used by things like the SqlMembershipProvider.
My question is, is there something that behaves similar to the Session but exists in the global scope?
I don't think there is anything like you need out of the box. I would do the following though:
User the application cache
Make the key the user ID or unique identifier
Store a Dictionary or some object list in the value for the user. Use this to store all the data you require.
Consider all prepending something on the user ID if you think there could be a conflict with the user unique identifier (eg domain etc)
Make sure to set an expiry on the cached data similar to the session (eg sliding)
Try passing the HttpContext.Current object to the method on your background thread. You should be able to access the session from the background thread through currentContext.Session assuming currentContext is the HttpContext parameter that was passed in.
See this blog post on how to safely access the HttpContext object from multiple threads.
No.
Since when application pool restarts all backgound activity die I suggest to think about moving user's state to your own database or external storage. Unfortunately you'll lose automatic session management benifits (sliding expiration), but if you need backgound activity it will work better - i.e. you'll be able to move your activity out of IIS process to separate process/machine if needed later.
I am working on a client server system, and am running into issues where multiple clients are executing an action at the same time. We are able to solve this by locking on the critical section of code, which ensures that the first client will complete the action before the second client enters the code block. My question is this: our server is also clustered, so multiple instances of the server itself can exist, which recreates the same problem as before. How could we solve this problem?
Thanks!
To expand on the problem: The first user is checking if an action is valid and getting a yes response. The second user is checking if an action is valid and also getting a yes response before the first user completes his/her action. But the first user's action should make the second user's action invalid. The problem is that the check occurs nearly simultaneously for each user.
It sounds like you have a bad design. Your service should not maintain state at all, if possible. That way, there would be no shared state to step on.
If you must maintain state, then you must interlock all access to that shared state. You can use the "lock" keyword in C# for this:
private static object _stateLocker = new object();
private static int _someSharedState = 0;
public void SomeAction()
{
lock (_stateLocker)
{
_someSharedState ++;
}
}
public int GetValue()
{
lock (_stateLocker)
{
return _someSharedState; }
}
More detail about your specific problem would be helpful to get a good solution - however, it's sounds like you need some form of interprocess/cross-server locking. There's nothing directly within the .NET framework (or Win32 APIs) to make this easy - you have to roll your own solution, I'm afraid.
You may want to look into some sort of clustered queuing mechanism so that only one process/thread is executing an action. This may or may not be easy in your overall design and the problem you are trying to solve. Alternatively, you could use a central authority (like a database) and a locking structure to determine if a lock for a particular action has already been started. The problem there is it's hard to make such a solution scale well due to the need to constantly interact with the database.
Another option you may have is to allow multiple process to attempt to process the same action simultaneously but to only allow one to complete. This can be tricky to ensure - but it's less expensive (computationally) to perform extra work and throw it away than to constantly check if someone else is already doing the work.