Terminate A Long Running Method

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Good Day,

I have a Windows Service that is responsible for processing somes files. One
method of the service invokes another method which may take a while to
complete its work. Something like this

pulbic class A
{

public void ProcessFile()
{

B Test = new B();
Test.DoWork();

}

}

public class B
{

public void DoWork()
{
//Long Running Method
}

}

Here is my problem. I need a way to signal the DoWork method that the
service has been called to stop and it need to finish whatever it is doing
gracefully and exit. So far the only solution I can come up with is to launch
the method on its own seperate thread. Then, the other method can monitor the
thread until it is done. If it needs to stop it can set a flag on the object
telling it to stop processing.

Is this really the best way to do this? Is there another way to achieve this
without launching a seperate thread?

Just looking for ideas. Thanks!

Dan
 
No I think that a thread is your only answer.

However there are a couple of options for the threads. You could
1) Use a .Net worker thread from the thread pool.
2) Create a class to wrap the thread and have a Stop property that
something else could set to tell the long running method to stop itself.
This assumes that the method can periodically check the value of the Stop
property. Otherwhise you'll have to take the brute force kill the thread
approach.

I like the second option myself but it really does depend upon what the long
running method is doing. The stuff I write tends to be protocol converters
so I have a thread monitoring a TCP connection whating for input which is
then translated into a different format and passed to another thread to be
sent out on a different connection. If you long running method is being used
to read from a database for instance or just to send a sing message and
process the response then a thread form the thread pool is probably better.

Paul.
 
Back
Top