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
Similar Messages:
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
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
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
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
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
May 4, 2010
Apart from blocking other threads reading from the cache what other problems should I be thinking about when locking the cache insert method for a public facing website.
The actual data retrieval and insert into the cache should take no more than 1 second, which we can live with. More importantly i don't want multiple thread potentially all hitting the Insert method at the same time.
The sample code looks something like:
public static readonly object _syncRoot = new object();
if (HttpContext.Current.Cache["key"] == null)
{
lock (_syncRoot)
{
HttpContext.Current.Cache.Insert("key", "DATA", null, DateTime.Now.AddMinutes(5), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
}
}
Response.Write(HttpContext.Current.Cache["key"]);
View 1 Replies
Mar 11, 2010
i'm trying to call a method with 3 parameters in a thread but i couldn't figure that out ..since it only accepts a non parametarized methods.
View 7 Replies
Mar 16, 2011
I want to introduce a slight wait during some testing functions, to simulate a server call. Is it sane to use Thread.Sleep(int) to introduce the wait or is there a better method to have the server wait?
Note, I'll be pausing long enough for me to visually see a sufficient lag, even tho I don't expect to see such a delay in the actual app. This is for me to visualize the actual delay that could occur.
I plan on running this both in the VS2010 local debugger webserver and in IIS 7. I'm on .NET 3.5
View 2 Replies
Jan 10, 2011
Assuming a static method like below is called from ASP.NET page,can a different thread(b) overwrite the value of s1 after the first line is executed by thread(a)?If so, can assigning parameters to local variables before manipulation solve this?
public static string TestMethod(string s1, string s2, string s3)
{
s1 = s2 + s3;
....
...
return s1;
}
Is there are a simple way to recreate such thread safety related issues?
View 3 Replies
Mar 26, 2011
I have a private static field in my Controller class in an MVC web application.
I have a static method in that controller that assigns some value to that static field, I want to apply lock on that static field until some other instance method in the controller uses the value stored in the static field and then releases it.
DETAILS:
I have a controller named BaseController having a static ClientId field as follows and two methods as follows:-
public static string ClientId = "";
static void OnClientConnected(string clientId, ref Dictionary<string, object> list)
{
list.Add("a", "b");
// I want the ClientId to be locked here, so that it can not be accessed by other requests coming to the server and wait for ClientId to be released:-
BaseController.clientId = clientId;
}
public ActionResult Handler()
{
if (something)
{
// use the static ClientId here
}
// Release the ClientId here, so it can now be used by other web requests coming to the server.
return View();
}
View 1 Replies
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
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
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
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
Jan 13, 2011
Is their a wayin sql server 2005 to change some type of setting on a data table so that it can not be updated or inserted into?
My problem is that I have a data table that is somehow being populated by an application. I have looked through all of the stored procs, views, functions and the C# code itself. I can't find out where or how it is populating a certain data table. So I figure if I can somehow make the table non updateable, then I can find out where the insert/update is occuring.
This would all occur in a test environment of course.
View 2 Replies
Feb 23, 2010
What I'm looking to do is lock the application so the admin can do maintenance for however long. All i want to do is be able to click a button on a "maintenance" page and it makes it so anyone who attempts to use the system and anyone who is already in the system is redirected to a page, if they try to do anything, that says the site is down for maintenance.
on postback, on redirect, etc. No Access until that button is clicked again to unlock.
View 4 Replies
Jan 17, 2011
Can I lock a record that is being edited, and restrict more than one user from editing the same record at the same time? using VB.NET or SQL Stored Procedure.
View 3 Replies
Jan 12, 2010
I intend to around existing code snippet (updating a Hashtable) with lock() block to prevent multiple threads (launched by ASP.NET web site) from simultaneously updating a Hashtable.
Bc this is first time I do in this measure, I need your advice on
Any performance overhead caution caused by lock() Any other issues you ever experienced similar to this scenarios.
View 3 Replies
Jun 29, 2010
I have a Button inside an UpdatePanel. How can I lock the page while the Button is clicked?
View 2 Replies
Apr 15, 2010
i want is to copy huge data from many tables to a master table in my database.
the copying process should executed once at the time from asp.net.
so if a user "A" start copying process, user "B" will not have the permission to copy untill the old process (started from user "A") complete.
what i am thinking to do is if its possible to lock "Copying Function" from using more than once at the time.
View 9 Replies
Oct 21, 2010
I have a deadlock problem that occurs every 5 minutes on SQL update. I get the following error randomly - means qurey failed one time every 200 calls. I'm using transaction scope to manage transaction.
code:
using(TransactionScope scope =
new
TransactionScope())
{
SELECT ... FROM TABLE1
UPDATE TABLE1 SET [F1] = @F1, [F2] = @F2, [F3] = @F3, [F4] = @F4, [F5] = @F5 WHERE UId = @UId
scope.Complete();
}
error:
System.Data.SqlClient.SqlException: Transaction (Process ID 51) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction
stack trace:
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at DAL.RunSQL(String query, SqlParameter[] parameters, Boolean openTransact) in C:prjDAL.cs:line 215
I took trace in SQL about deadlock and same SQL query is mentioned bu deadlock. I do not understand how to resolve this deadlock.
SQL log:
deadlock-list
deadlock victim=process5462718
process-list
process taskpriority=0 logused=0 waitresource=KEY: 20:72057597472604160 (ce004d0b917a) waittime=30 ownerId=5937428 transactionname=user_transaction lasttranstarted=2010-10-20T16:29:04.050 XDES=0x5d00280 lockMode=X schedulerid=2 kpid=2168 status=suspended
spid=65 sbid=0 ecid=0 priority=0 trancount=2 lastbatchstarted=2010-10-20T16:29:04.110 lastbatchcompleted=2010-10-20T16:29:04.110 clientapp=.Net SqlClient Data Provider hostname=IPTBEWKS017 hostpid=3112 loginname=iptuserjde isolationlevel=serializable (4) xactid=5937428
currentdb=20 lockTimeout=4294967295 clientoption1=671088672 clientoption2=128056
executionStack
frame procname=adhoc line=1 stmtstart=222 sqlhandle=0x0200000086adfa0c959ccbdd7ef0e31e854e3a987706ae38
UPDATE TABLE1 SET [F1] = @F1, [F2] = @F2, [F3] = @F3, [F4] = @F4, [F5] = @F5 WHERE UId = @UId
frame procname=unknown line=1 sqlhandle=0x000000000000000000000000000000000000000000000000
unknown
inputbuf
(@UId nvarchar(9),@F1 nvarchar(9),@F2 nvarchar(9),@F3 int,@F4 int,@F5 datetime)UPDATE TABLE1 SET [F1] = @F1, [F2] = @F2, [F3] = @F3, [F4] = @F4, [F5] = @F5 WHERE UId = @UId
process taskpriority=0 logused=0 waitresource=KEY: 20:72057597472604160 (cc0078aef293) waittime=88 ownerId=5937412 transactionname=user_transaction lasttranstarted=2010-10-20T16:29:04 XDES=0x2b028280 lockMode=X schedulerid=1 kpid=6788 status=suspended
spid=74 sbid=0 ecid=0 priority=0 trancount=2 lastbatchstarted=2010-10-20T16:29:04.050 lastbatchcompleted=2010-10-20T16:29:04.050 clientapp=.Net SqlClient Data Provider hostname=IPTBEWKS017 hostpid=3112 loginname=iptuserjde isolationlevel=serializable (4) xactid=5937412
currentdb=20 lockTimeout=4294967295 clientoption1=671088672 clientoption2=128056
executionStack
frame procname=adhoc line=1 stmtstart=222 sqlhandle=0x0200000086adfa0c959ccbdd7ef0e31e854e3a987706ae38
UPDATE TABLE1 SET [F1] = @F1, [F2] = @F2, [F3] = @F3, [F4] = @F4, [F5] = @F5 WHERE UId = @UId
frame procname=unknown line=1 sqlhandle=0x000000000000000000000000000000000000000000000000
unknown
inputbuf
(@UId nvarchar(9),@F1 nvarchar(9),@F2 nvarchar(9),@F3 int,@F4 int,@F5 datetime)
UPDATE TABLE1 SET [F1] = @F1, [F2] = @F2, [F3] = @F3, [F4] = @F4, [F5] = @F5 WHERE UId = @UId
resource-list
keylock hobtid=72057597472604160 dbid=20 objectname=dbipt_rc41_02.dbo.TABLE1 indexname=PK_TABLE1 mode=RangeS-U associatedObjectId=72057597472604160
owner-list
owner id=processdbbe40 mode=RangeS-S
waiter-list
waiter mode=X requestType=convert
keylock hobtid=72057597472604160 dbid=20 objectname=dbipt_rc41_02.dbo.TABLE1 indexname=PK_TABLE10 mode=RangeS-U associatedObjectId=72057597472604160
owner-list
owner mode=RangeS-S
waiter-list
waiter id=processdbbe40 mode=X requestType=convert
I have tried to analyse the trace with this post but unsuccessfully: [URL] UId is my primary key - I do select on F3 column just before in same transaction but i have also an index on F3 column.
->
Spid 65 is running this query (line 2 of proc [p1]):
UPDATE TABLE1 SET [F1] = @F1, [F2] = @F2, [F3] = @F3, [F4] = @F4, [F5] = @F5 WHERE UId = @UId
Spid 74 is running this query (line 2 of proc [p2]):
UPDATE TABLE1 SET [F1] = @F1, [F2] = @F2, [F3] = @F3, [F4] = @F4, [F5] = @F5 WHERE UId = @UId
View 5 Replies
May 26, 2010
-Edit- Important: I updated the code to not use obsoluete functions. Now only the NoSuchDirectoryException issue remains
Edit: NOTE i can bypass the NoSuchDirectoryException by creating the folder in a winform app and copy it. However i still have a LockObtainFailedException issue if i dont shut down properly.I have an issue with (Lucene.net 2.9.2
[https://svn.apache.org/repos/asf/lucene/lucene.net/tags/]. It throws a lock exception. After poking around i notice these things.
My code below works in an app bit when calling in Application_Start i get a NoSuchDirectoryException.Not closing the writer (as my code doesnt do below) i WILL get a LockObtainFailedException with the message
Lock obtain timed out: SimpleFSLock@<FULL_PATH> from either app or asp.net
These thread hinted when spawning threads they get less permissions then i do (but! my main thread has problems as well...) and one solution is to impersonate IIS. I am using visual studios 2010. I am not sure how full blown it is but my attempt to impersonate it failed.
So my question is how do i have lucene create the directory and not throw an exception if dont close the writer for some reason (such as power going out)?
http://stackoverflow.com/questions/2341163/why-is-my-lucene-index-getting-locked/2499285#2499285
http://stackoverflow.com/questions/1123517/lucene-net-and-i-o-threading-issue/1123981#1123981
static IndexWriter writer = null;
static void lucene_init()
{
[code].....
View 1 Replies
Feb 19, 2010
I have page with several textboxes, dropdowns, and check boxes on it. When I click my update button and the update happens, at that point all of the textboxes on the page are locked, I cannot click into any of them. The dropdowns and check boxes still work.
I do have an update panel on the page:
[Code]....
View 5 Replies
Mar 2, 2010
I have a website that show info to all users but if you are logged in you get access to more info and pages then unlogged user does. Can i use some sessions variables and include them in each of the pages ? What is the best way to do this. Also, what is the best way to make user stay logged in, sort of "Remember me" checkbox. Save a cookie on hdd ?
View 4 Replies