C# -.NET Multithreading & "thread Has Already Entered The Lock"

Feb 9, 2010

In an ASP.NET application, I have a resource that is protected by a ReaderWriterLockSlim.

Normal requests call EnterReadLock, access the resource, call ExitReadLock and return.

At one moment, I accidently forgot to put a call to ExitReadLock somewhere in my code. On the next request, I got an exception stating that the thread had already entered the lock.

Fair enough: if at the end of request A the thread does not exit the lock, and that same thread is used to process request B, and tries to enter the lock, it will throw.

Now, my question: is the following scenario possible? reasons?

thread begins to process request A
thread enters lock
thread does, say, sleep, or do some IO, and so becomes available same thread begins to process request B, while request A is "on hold"
thread enters lock !! throws !!


If yes, what other solution do I have to protect said resource? Bearing in mind I want to use a ReaderWriterLockSlim because I also have other thread that may write to the resource?

edit: add some details: 1) This happens in the ProcessRequest method of an HttpHandler which generates, caches and serves images. These images are expensive to generate. So, the first request will generate and cache the image, and we want to put the other requests on hold while generating.

2) We have not tried to "reproduce" -- at the moment we're trying to know if it is possible or not that the same thread begins processing a request while already waiting for the image to become ready.

3) I am aware of the LockPolicyRecursion but I am not sure I fully understand its purpose, and whether it would be OK to set it to SupportsRecursion in our case.

edit: going further...According to the document pointed to by Ryan below, a thread will block and not return to the pool as long as we don't engage into async operations. So once we've locked the thread waiting for EnterReadLock to complete, it won't return to the pool nor process any other request.

So 1) we should be safe but 2) we might starve the thread pool. Assuming we don't want to immediately return a dummy "please wait" image, what solutions do we have?

View 2 Replies


Similar Messages:

C# - Lock Thread.sleep Not Working With .NET Thread?

Jun 25, 2010

I have a password page and when someone enters an incorrect password I want to simply foil a brute force attack by having

bool isGoodPassword = (password == expected_password);

lock (this)
{
if (!isGoodPassword)
Thread.Sleep(2000);
}
I would expect that this would allow all correct passwords without stalling, but if one user enters a bad password another successful password from a different user would also be blocked. However, the lock doesn't seem to lock across ASP.NET threads.

View 4 Replies

Multithreading - Want To Create A Thread In A Mvc Application?

Nov 5, 2010

I want to create a thread in a asp.net mvc application. What will happen?

A) Thread will die when request ends and the response is sent.

B) Thread will continue to run and response will be sent when thread terminates.

C) Thread will run without blocking the response and die when it have completed it's task

View 1 Replies

C# - Looking For .NET Lock Thread Method?

Mar 30, 2010

I'm developing an ASP.NET forms webapplication using C#. I have a method which creates a new Order for a customer. It looks similar to this;
private string CreateOrder(string userName) {
// Fetch current order
Order order = FetchOrder(userName);[code]....

The problem here is, it is possible that 1 customer in two requests (threads) could cause this method to be called twice while another thread is also inside this method. This can cause two orders to be created.

How can I properly lock this method, so it can only be executed by one thread at a time per customer?

I tried;

Mutex mutex = null;
private string CreateOrder(string userName) {
if (mutex == null) { [code]....

This works, but on some occasions it hangs on WaitOne and I don't know why. Is there an error, or should I use another method to lock?

View 5 Replies

Lock Ever Get Stuck Locked Due To An Unexpected Thread Death Or Similar

Aug 11, 2010

I have an ASP.NET site that I am maintaining. Currently it has code that on first access (and other times too) goes and does a bunch of data caching by writing it to files. Currently it has no locking so we cna get problems with multiple people accessing the site and multiple threads trying to write to the files at the same time. This is obviously bad so I am going to implement some locking.

My current modified code just puts a simple lock around a section of code so that later requests just wait until the first request is done.

My concern is that I haven't used locks much so I just want to check if there is any situation in which that lock could not get released? For example I have no idea what happens if that first thread is killed (eg the web server decides its run too long and shuts it down). Does the lock get automatically freed at that point? Is there anything else I need to think about while doing this?

Edit to add:Here is what I think are relevant bits of Code in case there is anything I am doing stupid...

I am using private lock objects accessed through a dictionary and don't do anything much more than wrap some code in a SyncLock statement (equivalent of C# lock).

Public Shared Sub CheckAllVariables(ByVal SourceName As String, ByVal cn As HttpContext)
...
Do While dr.Read
projectID = dr.GetInt32(dr.GetOrdinal("ProjectID"))
Dim cacheLockObject As Object = GetCacheLockObject(projectID)code]....

Should I wrap access to the GetCacheLockObject function in a lock to prevent the possibility of two threads going in simultaneously and both finding the cache lock doesn't exist and then both creating it and returning different ones? I'm a little unused to having to consider thread safeness (assumign I am using that term correctly).

View 2 Replies

Cross-thread Operation Not Valid: Accessed From A Thread Other Than The Thread It Was Created On

Apr 2, 2010

I want to remove checked items from checklistbox (winform control) in class file method which i am calling asynchronously using deletegate. but it showing me this error message:-

Cross-thread operation not valid: Control 'checkedListBox1' accessed from a thread other than the thread it was created on.

i have tried invoke required but again got the same error. Sample code is below:

[code]....

View 1 Replies

Visual Studio :: Debug A Multi Thread Program To See Local Variables Of Each Thread Using 2008

Jan 27, 2010

How can we debbug a multi-thread program to see local variables of each thread using visual studio 2008.

View 1 Replies

Architecture :: How Can Thread Update A Variable Shared With The Main Thread

Nov 24, 2010

I'm new to threading and have used it successfully, but limited. I can spawn a thread and have the main thread reference variables in the spawned thread, but I don't know how to allow the spawned thread to reference (and update) variables in the main thread.

Any example threading code I've seen on the web appears to be WAY more complicated than what I do, so I am unable to understand or integrate into my code.

Here is a quick example of how I use threading:

[code].....

View 3 Replies

What Are The Differences Between Currently Executing .NET Thread And Win32 Thread

Mar 24, 2010

I am reading the Asp.net security documentation on msdn.I come across these tow terms and get really confused.

# WindowsIdentity = WindowsIdentity.GetCurrent()

which returns the identity of the security context of the currently executing Win32 thread.

# Thread = Thread.CurrentPrincipal

which returns the principal of the currently executing .NET thread which rides on top of the Win32 thread.

View 1 Replies

Web Forms :: Use Thread.sleep Method For A Particular Thread?

Aug 27, 2010

I want a example of multithreading .i want to use it in a web form not on console.i am using C#.net .and how to use thread.sleep method for a particular thread.

View 5 Replies

Vb.net - .net Multithreading With Synclock?

Jan 31, 2011

i have some test code which i run at every load of a page in my asp.net website

this is the code

Sub TryThreads()
Dim t1 = New Thread(AddressOf TryLock)
t1.Priority = ThreadPriority.Lowest[code]...

the "dotrace" simply add a record to a log table in the db.now the right result would be that i should have the entries in the db in order "entered","exiting","exited"but actually when i look in the db i see first 2 "entered" then 2 "exiting" etc.meaning that the multithreading is working ok, but not the synclock is that correct?the real code will be adding records to the db and might be called from several pages of different sessions, but the same code must not run twice concurrently.

EDIT:in response to Sashas wonderful post i changed my code to a class (it was in a module) and now it looks like this:

Public Class CheckClass
Property LockObject As Object
Get [code]...

if i open multiple pages at once, they still clash some times. but if i'm correct, the issue is now not with the synclock as much as with the httpruntime.cache, because when using a standard property, on one page, the code works 100%. so how can i make sure that 2 threads, even from totally different sessions never run the trylock simultaneously?

View 1 Replies

Multithreading As A Web Method?

Feb 3, 2010

I'm working on my project, I want to ask is it possible to create multithreading in the web method at the web server side instead, not the client side.

View 3 Replies

Multithreading Accepts Value And Return Value?

Dec 18, 2010

I wrote the following code to return a pdf report. The code is based on a multi-threading sample code. Can you guys provide some feedback about it, I am new to mulit-thread.

public delegate void StreamResultDelegate(Stream streamResults);

public class GenerateReport
{[code].....

View 2 Replies

Multithreading In Dotnet Apps?

Sep 30, 2010

Multithreading in dotnet apps?

View 3 Replies

Web Forms :: Implement Multithreading Into The Web Application?

Aug 27, 2010

i want to impliment multithreading into my web application how to do that..

i have already knew the concept of multithreading but want to impliment into application..

i have developped an application this application runs correctly for 400 users but when more user hits the server than the application fails to respond...

how improve the performance of the application..is this problem is related to the database server of the application server.

View 1 Replies

Web Forms :: Implement MultiThreading In Web Applications?

May 7, 2015

i want know how i can insert data to database in background process

like when you like or unlike a post in facebook

View 1 Replies

Multithreading - How Are Threads Tied To Requests Through Http.sys, IIS

Jan 29, 2011

I'm currently reading a lot about node.js. There is a frequent comparison between servers using a traditional thread per request model (Apache), and servers that use an event loop (Nginx, node, Tornado).

I would like to learn in detail about how a request is processed in ASP.NET - from the point it is received in http.sys all the way up to it being processed in ASP.NET itself. I've found the MSDN documentation on http.sys and IIS a little lacking, but perhaps my google-fu is weak today. So far, the best resource I have found is a post on Thomas Marquardt's Blog.

Could anyone shed more light on the topic, or point me to any other resources?

View 1 Replies

Multithreading - .net ThreadPool - Long Running Operation.

Jan 27, 2010

My application is a asp.net 3.5 running on iis 6 (windows 2003)

This application is serving 1000's of users daily (100-500 users online).

I want to send an email newsletter to customers weekly.

Around 200,000 emails every time.

This is the code im using:

ThreadPool.QueueUserWorkItem(new WaitCallback(AsyncProcessMailerQueue), null);

private static void AsyncProcessMailerQueue(object data)[code]....

When testing this locally (on my dev machine) i see the application is working alot slower.

Is there a better way to write this code? Should i use ThreadPool.QueueUserWorkItem or create a new thread using Thread t = new Thread(new ThreadStart(DoWork)); ? Will it be better to create a totally seperate application for the purpose of sending the newsletters. will that help if ill run this application on the same machine?

i've seen other posts here talking about ThreadPool vs Thread but its seem no one is sure which is better.

View 3 Replies

Use AJAX Or Multithreading To Speed Up Page Load?

Jan 30, 2011

I have a page that has 5 sections. Each section takes about 1 second to render.

Page_Load()
{
RenderSection1(); //1 sec
RenderSection2(); //1 sec
RenderSection3(); //1 sec
RenderSection4(); //1 sec
RenderSection5(); //1 sec
}

I would like to speed up the loading of this page. But at the same time make sure that it don't slow down performance of other parts of web application and also do not crash the IIS.

The are several approaches:

Use AJAX requests. Needs to be MVC style requests to Controller or Web Service. Using UpdatePanel around each section will not work - since if I try to submit refreshes to multiple UpdatePanels at the same time using approach here: [URL], the last request will always win: [URL] Use ASP.NET threads described in answer to right way to create thread in ASP.NET web application. So I would use a separate thread for each call: RenderSection1, RenderSection2, etc... Move the logic that takes up time, usually DB requests, into Application Service class in another DLL or External Web Service. Something like

OrderDTO GetDataForViewOrder(int orderID)
{
}

and use multiple threads in that DLL. This approach seems to provide the best scalability, but also introduces UI details into Application Services layer.

View 3 Replies

Web Forms :: Upload Large Excel File - Use Multithreading?

Mar 7, 2011

i have a large excel file which has 1 lakh row , i want to insert these data in my table i am using entity framework for insert but it takes more than 45 minutes to insert which is too much, i want to speed up the uploading process what should i do. can I use multithreading for it if yes then how i can use? if any other way to do this process.

View 1 Replies

Multithreading - Page Running On IIS Make Use Of Multicore Processors?

Jul 8, 2010

I've got an ASP.net page that runs a script which takes anywhere between 1 second and 10 minutes to run dependant on the parameters passed in to it. My question is, if the server is multicore, will this script automatically make use of all the processors, or is it constricted to one.

View 3 Replies

C# - Recursive Function MultiThreading To Perform One Task At Time?

Jun 14, 2010

I am writing a program to crawl the websites. The crawl function is a recursive one and may consume more time to complete, So I used Multi Threading to perform the crawl for multiple websites. What exactly I need is, after completion crawling one website it call next one (which should be in Queqe) instead multiple websites crawling at a time.I am using C# and ASP.NET.

View 4 Replies

Multithreading - When Serve A Webpage -, Can Render The Various Controls On The Page In Parallel

Aug 10, 2010

When I serve an ASP.NET page, can I render the various controls on the page in parallel?

I have a few Telerik controls (RadGrids) on the page and when I step through the page being loaded, it seems as though the controls are databound and rendered serially.

Maybe this behavior is because I am hooked in with the debugger.

Is there anyway to load the page and have select controls build on separate threads? Is that even conceptually possible or must it be done sequentially?

View 2 Replies

State Management :: Session Lost When Multithreading Though ( There Is A Wait Call ! )?

Mar 9, 2011

I am creating a multithreading application and I am using countdownevent to signal my object arround 3 times and using wait , but somehow the session goes null , although I am setting a breakpoint after mycountdownevent.wait() and the breakpoint isnt reached , that means the execution is not done...so can someone tell me what is wrong?? here is my code :

this is the main thread

[Code]....

this is the upload image method :

[Code]....

and this is a property for the countdown event :

public
CountdownEvent
_3adasehCountDownEvent;

View 7 Replies

Using 'Lock' In Web Applications?

Nov 30, 2010

A few months ago I was interviewing for a job inside the company I am currently in, I dont have a strong web development background, but one of the questions he posed to me was how could you improve this block of code.I dont remember the code block perfectly but to sum it up it was a web hit counter, and he used lock on the hitcounter.

lock(HitCounter)
{
// Bla...
}
However after some discussion he said, lock is good but never use it in web applications!What is the basis behind his statement? Why shouldnt I use lock in web applications?

View 6 Replies







Copyrights 2005-15 www.BigResource.com, All rights reserved