Pergunta

I am using the following code for a critical section of a web page

if(Monitor.TryEnter(lockObj,60000))
{
  try{
       //write some things to a file
     }
  finally
  {
    Monitor.Exit(lockObj);
  }
}

Here, lockObj is a static member of the class. My question is, what happens if the user closes the web page or the browser while the critical section is being executed? Does lockObj remain locked for future page requests?

Foi útil?

Solução

Nothing automatically occurs when the user closes a browser window or navigates to another page, if the request is still processing. This is why the HttpResponse.IsClientConnected property exists - so your code can perform appropriate checks as and when you can do something useful.

If a timeout occurs on the server side, then the finally block should operate at around that time and the lock will be released. Whether it is safe for the lock to be released at this time is something only you can determine - the lock must have been put there for a reason, and if a timeout occurs, that may mean that the (shared, lock requiring state) isn't stable for whoever next acquires the lock.

But these are two very different sets of issues.

Outras dicas

If you somehow manage to kill the executing thread inside of

try {
  //write some things to a file
}

you might have some issues. But for all realistic cases with exceptions the code will function.

In effect, just avoid Thread.Abort.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top