How to close NHibenrate session when using the ThreadPool? - c#

Since threads are reused over and over by the ThreadPool I can't tell when to close NHibernate sessions for each thread to release used up resources.
Should I spawn my own threads (to ensure they are unique) or there is a better way to do this using the ThreadPool?

I fail to see the problem. You might to have to elaborate or add some code in your question.
Each thread has it's own method. Simply allocate the session in the beginning of the method and clean it up in the end. The same applies when you are using a thread pool thread.
Don't forget to wrap all thread code in a try/catch, or your application will crash if an exception is unhandled.

I'd have it set up so that there is one session per thread. This is probably the easiest way to make sure that you don't run into issues where you have a thread terminating a session that is in use by another thread.

Related

Find which thread currently owns a lock so I can kill it

I need to find out which thread currently owns the lock.
I'm writing a multithread server using ThreadPool that hosts independent application instances. When shutting down an application instance I call Monitor.TryEnter to either acquire the lock or timeout. If a timeout occurs I need to get which thread owns the lock so I can abort it.
If there are no bugs in the applications I would never need to do this as each worker would lock and unlock the application instance on entry and exit to the application. But if there IS a bug, and for whatever reason the worker doesn't exit and is either deadlocked or stuck in an endless loop I want to be able to kill that thread and application instance, while letting the rest of my server live on. The application instance at this point is a lost cause.
Seems like a pretty straight forward requirement, but couldn't find anything built in to do it.
One workaround would be to add a Thread member in the same context as the lock and have each thread update it as it acquires the lock. But that relies on everyone ALWAYS remembering to update it when a lock is acquired.
You think the thread control as a top down hierarchy, but this is not the right way of thinking in the matter of multithreaded applications. If a Thread has a timeout or something else went wrong during its execution, the thread itself has to take care of releasing the lock and ending itself.

C# threading deadlock

I have a multi-threaded program in C#. What is the best way to prevent deadlock in practice?
Is it timedlock?
Also, what is the best tool available to help detect and prevent the deadlock?
Thank you very much.
Deadlocks typically occur in a few scenarios:
You are using several locks and not locking/unlocking them in the correct order. Hence, you may create a situation where a thread holds lock A and needs lock B, and another thread needs lock A and holds lock B. Neither of them can proceed. This is because each thread is locking in a different order.
When using a reentrant lock and locking it more times than you are unlocking it. See this related question: why does the following code result in deadlock
When using Monitor.Wait/Monitor.Pulse as a signaling mechanism, but the thread that must call Wait does not manage to reach the call by the time the other thread has called Pulse and the signal is lost. You can use the AutoResetEvent for a persistent signal.
You have a worker thread polling a flag to know when to stop. The main thread sets the flag and attempts to join the worker thread, but you forgot to make the flag volatile.
It's not C# specific. You should always acquired in some well-defined order.
There is much information in internet, for example, you might take a look here
http://www.javamex.com/tutorials/threads/deadlock.shtml

killing a thread which is in blocking state

I have a thread which blocks itself on some lock.Now For some condition I want to kill the thread in c#.
But the thing is that in thread.abort does not guarantees that it will kill the thread.
If you really want a guarantee of thread death, your best option is to start a new process.
There is an excellent thread that discusses many of the possible pitfalls of thread.abort here.
Assuming you want to kill the thread in a deterministic way when it encounters deadlock . Right ?
Yes thread abort does not guarantee termination but it is almost always a bad idea to use Thread.Abort.
If there was a way to kill the thread instantaneously it can lead to bigger problems . If this thread has taken lock on some resource , is in the middle of some uncommitted transaction etc ,and the thread holding these resource is abruptly killed no other thread can work on these resources.
Best suggestion I can give is is to fix the deadlock issue rather than masking it.

Finding blocking calls in VS2010 solution

I've been tasked with removing blocking calls from a C# app. Turns out this is a requirement of the environment it'll be running on. I understand the concept of a blocking call, however, I'm not sure where to begin finding existing blocking calls.
So a few questions:
For any given function, how can I tell whether or not it is blocking? Is there any way besides looking up the documentation?
Is there any way to search for blocking in a project or solution? Eg. some plug-in that could tell me?
There's no automatic way I know of to find blocking calls. Most blocking code is used for thread or process synchronization such as lock, Monitor.Enter, Mutex and Semaphore/SemaphoreSlim waits, CountdownEvent and Barrier class use. There's also SpinLock and ReaderWriterLock/ReaderWriterLockSlim locks which block.
There are several Thread calls that are blocking. Thread.Sleep can technically be considered a blocking call, though it lasts a finite amount of time. Thread.Join waits for other threads to finish and is thus blocking.
For and While loops can be considered blocking as they will run until they are done, but usually they will use one of the calls above (especially lock) if they are waiting on a specific variable updated in another thread.
Keep in mind that removing any of these is likely to have a serious negative impact on thread safety.

C# Communication between threads

I am using .NET 3.5 and am trying to wrap my head around a problem (not being a supreme threading expert bear with me).
I have a windows service which has a very intensive process that is always running, I have put this process onto a separate thread so that the main thread of my service can handle operational tasks - i.e., service audit cycles, handling configuration changes, etc, etc.
I'm starting the thread via the typical ThreadStart to a method which kicks the process off - call it workerthread.
On this workerthread I am sending data to another server, as is expected the server reboots every now and again and connection is lost and I need to re-establish the connection (I am notified by the lost of connection via an event). From here I do my reconnect logic and I am back in and running, however what I easily started to notice to happen was that I was creating this worker thread over and over again each time (not what I want).
Now I could kill the workerthread when I lose the connection and start a new one but this seems like a waste of resources.
What I really want to do, is marshal the call (i.e., my thread start method) back to the thread that is still in memory although not doing anything.
Please post any examples or docs you have that would be of use.
Thanks.
You should avoid killing the worker thread. When you forcibly kill a Win32 thread, not all of its resources are fully recovered. I believe the reserved virtual address space (or is it the root page?) for the thread stack is not recovered when a Win32 thread is killed. It may not be much, but in a long-running server service process, it will add up over time and eventually bring down your service.
If the thread is allowed to exit its threadproc to terminate normally, all the resources are recovered.
If the background thread will be running continuously (not sleeping), you could just use a global boolean flag to communicate state between the main thread and the background thread. As long as the background thread checks this global flag periodically. If the flag is set, the thread can shut itself down cleanly and exit. No need for locking semantics if the main thread is the only writer and the background thread only reads the flag value.
When the background thread loses the connection to the server that it's sending data to, why doesn't it perform the reconnect on its own? It's not clear to me why the main thread needs to tear down the background thread to start another.
You can use the Singleton pattern. In your case, make the connection a static object. Both threads can access the object, which means construct it and use it.
The main thread could construct it whenever required, and the worker thread access it whenever it is available.
Call the method using ThreadPool.QueueUserWorkItem instead. This method grabs a thread from the thread pool and kicks off a method. It appears to be ideal for the task of starting a method on another thread.
Also, when you say "typical ThreadStart" do you mean you're creating and starting a new Thread with a ThreadStart parameter, or you're creating a ThreadStart and calling Invoke on it?
Have you considered a BackgroundWorker?
From what I understand, you just have a single thread that's doing work, unless the need arises where you have to cancel it's processing.
I would kill (but end gracefully if possible) the worker thread anyway. Everything gets garbage-collected, and you can start from scratch.
How often does this server reboot happen? If it happens often enough for resources to be a problem, it's probably happening too often.
The BackgroundWorker is a bit slower than using plain threads, but it has the option of supporting the CancelAsync method.
Basically, BackgroundWorker is a wrapper around a worker thread with some extra options and events.
The CancelAsync method only works when WorkerSupportsCancellation is set.
When CancelAsync is called, CancellationPending is set.
The worker thread should periodically check CancellationPending to see if needs to quit prematurely.
--jeroen

Categories