First off – apologies if this or a similar question has been asked before. It feels like it should have been, but I’ve been unable to find one.
I have a third party assembly with a method I’m calling, this method has parameters taking a list of objects (in concept, not List<object>) and returns a result after a potentially long running algorithm.
I call this method on a different thread to preserve UI responsiveness. And it gets called quite regularly and with a different list of values. This means that it’s often running when I want to re-run it. The problem I have is that the creation of the new thread is quite naive so it fires off a new one each time – this results in multiple threads running with different input parameters. What I actually want to happen is for any existing threads to die as I’m no longer interested in their output.
I’m not very familiar with multi threading best practises so I would really like some suggestions on the best way to approach this problem.
(I’m using 3.5 so no TPL)
EDIT
I cracked out Reflector to see what was going on inside and a lot of the code is marked protected so I’m pretty certain I can inherit and wrap the call in a check to quit early as per the answers below.
You could treat this as a Producer/Consumer pattern.
Instead of starting a Thread, post (produce) a new Datapacket.
The Consuming Thread should monitor the queue and start on a new packet when it arrives.
Note that stopping the Thread is your main issue here. Don’t even look at Thread.Abort(). You need to build that logic into the thread-code.