C# / ASP.NET - Web Application locking - c#

I'm working on a C#/ASP.NET web application, and I have a number of situations where I need to do locking. Ideally, I want the locks to act independently, since they have nothing to do with each other. I've been considering [MethodImpl(MethodImplOptions.Synchronized)] and a few ways of using lock(), but I have a few questions/concerns.
It seems like MethodImplOptions.Synchronizedwill essentially dolock(this)`. If that's the case, it seems like a thread entering any synchronized method would block all other threads from entering any synchronized method. Is that right? If so, this isn't granular enough. At that point, it seems like I may as well use Application.Lock. (But please correct me if I'm wrong.)
Concerning lock(), I'm trying to figure out what I should pass in. Should I create a set of objects solely for this purpose, and use each one for a different lock? Is there a better way?
Thanks in advance!

My preference is to create an object specifically for the lock.
private object lockForSomeResource = new object();
in the class that is managing the contentious resource.
Jeff Richter posted an article I read some time ago that recommended this.
You need to think carefully about designing these as a hierarchy if there is any code within a lock that needs another lock. Make sure you always request them in the same order.

I have posted a similar question on this forum, that may help you. Following is the link
Issue writing to single file in Web service in .NET

You can expose some static reference or a singleton, and lock() that.
Maybe you can care to explain why you need such locking and what you will use it for?

Creating discrete object instances at static/application level is the best way for plain exclusive locking.
Should also consider if reader/writer lock instances at application level could also help improve your application concurrency e.g. for reading and updating lists, hashes etc.

Related

MemoryCache over Threads

I'm currently investigating some code which has a cache layer which at the bottom level uses the MemoryCache class. This is a c# Windows Service app so not web/IIS. There is a section of the code which spawns off a number of threads in which it creates and executes some code in a POC to perform some calculations. These are then stored in the above mentioned cache layer. What is been seen is it looks like cached values seem to be getting stored per thread and not at apication level. I thought that MemoryCache was a Singleton that would sit out side of the individual threads.
Can anybody confirm this behaviour would be expected?
Many thanks for any comments.
A MemoryCache is thread-safe but there is no reason to assume it's a singleton. If you want different threads to access the same MemoryCache instance you need to give them all a reference to the same instance (either as a singleton (really bad) static (still bad) or through argument passing as dependency injection (good)).
The simple way to do it (which does use global state) is to access the default memory cache:
var cache = MemoryCache.Default; // not really a good idea and harder to test, works
You can find the specific docs here. Make sure to configure it in your app/web.config file.

Reusing the session of the thread with NHibernate

I know several topics on the subject have been discussed, because I have been reading a lot to try to resolve my issue, but somehow they happen to not fulfill my needs (maybe for the lack of detail). Anyway, if you think some specific 'topic' might be useful, please link it.
I'm developing a desktop application with WPF (and MVVM) and I'm using NHibernate. After researching about possible ways to manage my session, I have decided to use the session-per-form approach. By this way, I think I can fully use the features of NHibernate like lazy-loading, cache and so on.
As I'm working with a database, I don't want to freeze my UI while I'm loading or saving my entities, so I thought I should use a dedicated thread (in each form, which I think simplifies the development) to handle the database interaction. The problem, though, is how I should 'reuse' the thread (supposing I have a session associated with that thread) to make my 'database calls'.
I think I couldn't use TPL because I'm not guaranteed that the two tasks would run in the same thread (it's not even guaranteed that they will be run in different threads than the invoker)
I would prefer to use session-per-form, as I have seen similar discussions that end by using session-per-conversation or something like that. But anyway, if you find that session-per-conversation would be better, please tell me (and hopefully explain why)
Threads don't provide a way to directly run more than one method, so I think I would have to 'listen' for requests, but I'm still unsure if I really have to do this and how I would 'use' the session (and save it) only inside the thread.
EDIT:
Maybe I'm having this problem because I'm confusing thread-safety with something else.
When the NHibernate documentation says that ISession instances are not thread-safe, does it means that I will (or could) get into trouble if two threads attempt to use it at the same time, right? In my case, if I use TPL, different threads could use the same session, but I wouldn't perform more than one operation in the same session at the same time. So, would I get into trouble in that situation?
If I may make a suggestion, desktop applications are poorly suited to interact with the database directly. The communication is not encrypted and it's really easy for someone with even the slightest amount of know-how to grab the database password and begin messing with records using a SQL connection and corrupt your database.
It would be better to create a web service with authentication that stands between the desktop application and the database as you could create credentials for each person and every transaction would be forcibly subjected to your various business rules.
This would also take care of your threading issue as you would be able to create HTTP connections on another thread with little to no trouble concerning session management. A cookie value is likely all that would be required and RestSharp makes this fairly trivial.

What is the design pattern to be used to deal with multiple requests to a share resource in IIS

I have a Lucene Index on a central file system. In my IIS application, I have methods to query the index and another to update the index.
To update the index, I have to lock the file until the changes are committed. My problem in implementing this is choosing the best design pattern to maintain good concurrency.
Am I best off using a static updater class that uses a lock about a static object?
If another request to update the index comes in while the lock is active, will the request 'wait' or will it return an exception? If it cannot wait, should I implement a thread safe FIFO type object with the series of operations to conduct sequentially?
What you want is something based on the one reader many writers design pattern.
You should probably update the index as a completely separate operation, in a windows service in some fashion.
Is that an option? Or do you need it consistently 24/7? I suspect you probably don't.
Furthermore, even if you do, you could possibly have your own 'cache' of newly added/removed items that you pass through before going to Lucene.

A method for high-load web site logging to file?

I need to build in click and conversion tracking (more specific and focused than IIS log files) to an existing web site. I am expecting pretty high load. I have investigated using log4net, specifically the FileAppender Class, but the docs explicitly state: "This type is not safe for multithreaded operations."
Can someone suggest a robust approach for a solution for this type of heavy logging? I really like the flexibility log4net would give me. Can I get around the lack of safe multi-threading using lock? Would this introduce performance/contention concerns?
While FileAppender itself may not be safe for logging, I'd certainly expect the normal access routes to it via log4net to be thread-safe.
From the FAQ:
log4net is thread-safe.
In other words, either the main log4net framework does enough locking, or it has a dedicated logging thread servicing a producer/consumer queue of log messages.
Any logging framework which wasn't thread-safe wouldn't survive for long.
You could check out the Logging Application Block available in the Microsoft Enterprise Library. It offers a whole host of different types of loggers, as well as a handy GUI configurator that you can point to your app.config\web.config in order to modify it. So there's not need to sift through the XML yourself.
Here's a link to a nice tutorial on how to get started with it:
http://elegantcode.com/2009/01/20/enterprise-library-logging-101/
I'm also interested in the answer, but I'll tell you what I was told when I tried to find a solution.
An easy way around it would be to use something like an SQL database. If the data you want isn't well suited for that, you could have each page access write it's own log file and then periodically merge the log files.
However, I'm sure there's a better solution.
When using syslog, you won't be having any threading issues. Syslog, sends the loglines using UDP to a logdaemon (could potentially be on the same machine).
Works especially great if you have more running processes/services, since all log lines are aggregated in 1 viewing tool.
if you expect really heavy loads, look at how the guys from facebook do it: http://developers.facebook.com/scribe/ You can use their opensource logtool. I don't think you'll hit their kind of load just yet, so you should be safe for some time to come!
R

Is EPiServer threadsafe?

I can't find any information about this on either www.episerver.com or world.episerver.com, anyone knows?
From what I've seen Episerver uses two mechanisms to achieve thread-safety:
Locking (when initializing expensive resources)
Immutable data (when passing page data around)
thread safe is a nebulous concept. In this particular case, if you are sharing data between different requests, it is not. Otherwise by the nature of web requests it is.
Yes, per definition it is thread safe because it runs under a web service that uses threads to execute (so it has to be thread safe otherwise it is a bug, and there has been o few of those bugs – but no one reported for CMS R2 what I can see in the bug list).

Categories