3

I have a service running some different tasks in a loop until the service is stopped. However one of these tasks i calling a web service and this call can take several minutes to complete. I want to be able to stop the service instantly, 'cancelling' the web service call without calling Thread.Abort because that causes some strange behavior even if the only thing the thread is doing is calling this web service method.

How can i cancel or break from a synchronous method call (if it's even possible)? Or should I try a different approach?

I have tried to use the AutoResetEvent and then calling Thread.Abort which is working fine in the below code sample, but when implementing this solution in the actual service I get some unexpected behavior probably because of what's going on in the external libraries I'm using.

AutoResetEvent and Thread.Abort:

class Program
{
    static void Main(string[] args)
    {
        MainProgram p = new MainProgram();
        p.Start();
        var key = Console.ReadKey();
        if (key.Key == ConsoleKey.Q)
            p.Stop();
    }
}

class MainProgram
{
    private Thread workerThread;
    private Thread webServiceCallerThread;
    private volatile bool doWork;

    public void Start()
    {
        workerThread = new Thread(() => DoWork());
        doWork = true;
        workerThread.Start();
    }

    public void Stop()
    {
        doWork = false;
        webServiceCallerThread.Abort();
    }

    private void DoWork()
    {
        try
        {
            while (doWork)
            {
                AutoResetEvent are = new AutoResetEvent(false);
                WebServiceCaller caller = new WebServiceCaller(are);
                webServiceCallerThread = new Thread(() => caller.TimeConsumingMethod());
                webServiceCallerThread.Start();

                // Wait for the WebServiceCaller.TimeConsumingMethod to finish
                WaitHandle.WaitAll(new[] { are });

                // If doWork has been signalled to stop
                if (!doWork)
                    break;

                // All good - continue
                Console.WriteLine(caller.Result);
            }
        }
        catch (Exception e)
        {
            Console.Write(e);
        }
    }
}

class WebServiceCaller
{
    private AutoResetEvent ev;
    private int result;

    public int Result
    {
        get { return result; }
    }

    public WebServiceCaller(AutoResetEvent ev)
    {
        this.ev = ev;
    }

    public void TimeConsumingMethod()
    {
        try
        {
            // Simulates a method running for 1 minute
            Thread.Sleep(60000);
            result = 1;
            ev.Set();
        }
        catch (ThreadAbortException e)
        {
            ev.Set();
            result = -1;
            Console.WriteLine(e);
        }
    }
}

Can someone suggest a solution to this issue?

4
  • without knowing what you external libraries are doing any answer would be pure speculation... you could in theory just work with some "flag" which you check in that thread at points when it would be safe to "abort"...
    – Yahia
    Feb 14, 2012 at 8:04
  • Can you write your WebServiceCaller and thread mechanism so that it can be orphaned and left to die on its own when it returns? Clear your doWork flag, stop waiting on the thread/event, set any callbacks to null, forget about it, carry on. When the long web service call eventually returns and the thread sets its ref to null and terminates itself, no-one notices or cares, (sob..). Feb 14, 2012 at 8:18
  • I could, but then my service (and it's process) would not be stopped completely until the WS call returns. Feb 14, 2012 at 8:20
  • Oh - you want to completely end the whole service process - can you just call ExitProcess() then? Feb 14, 2012 at 8:27

3 Answers 3

5

Try this

public void Start()
{
    workerThread = new Thread(() => DoWork());
    doWork = true;
    workerThread.IsBackground = true;
    workerThread.Start();
}

A thread is either a background thread or a foreground thread. Background threads are identical to foreground threads, except that background threads do not prevent a process from terminating. Once all foreground threads belonging to a process have terminated, the common language runtime ends the process. Any remaining background threads are stopped and do not complete.

For more details see http://msdn.microsoft.com/en-us/library/system.threading.thread.isbackground.aspx

3
  • Why have I not found this one while searching. This could definitely sound like a solution. I will try this one out and return with the result. Feb 14, 2012 at 8:27
  • +1 I never considered that - I assumed that any thread in a service would be set as a background thread. Feb 14, 2012 at 8:30
  • +1 as @MartinJames I also thought it would run in the background. However the solution I'm going for is running it async. Feb 14, 2012 at 11:12
2

The solution is really this simple: Don't make calls that block for several minutes unless you want to block for several minutes. If there is no way to do a particular thing without blocking, potentially for several minutes, complain loudly to whoever wrote the code that imposes that painful requirement (or fix it yourself, if possible).

Once you've made the call, it's too late. You're committed. If the function you are calling doesn't provide a safe way to abort it, then there's no safe way.

10
  • You can execute the Blocking Call in a completely seperate thread and just kill that Thread if you need to stop it. Feb 14, 2012 at 8:10
  • 1
    @CodingBarfield How do you know that's safe? What if you kill that thread while it holds a lock that a critical thread (say one doing writes to a file that is currently in an inconsistent state) needs in order to shut down cleanly? Feb 14, 2012 at 8:11
  • Well, if there really is no other way around this then maybe I should look into another way of solving this. Feb 14, 2012 at 8:12
  • @NicklasJepsen Can you avoid making the blocking call in the first place? Does the API you are using offer a non-blocking, limited-time blocking, asynchronous, or cancellable version? (If not, complain loudly to whoever provided it. A function that might block for minutes that is uncancellable and with no other way to get the same functionality is just bad design.) Feb 14, 2012 at 8:13
  • 1
    I actually managed to make an async call and I think it is the most correct solution to the problem. Thanks for the input! Feb 14, 2012 at 11:10
0

As all you want to do is make one an asynchonrous web service call at a time and on each response make another call you can dispense with the worker thread and simply make an aynchronous call, register a callback and make another async call from the callback:

class Program
{
    private static WebServiceCaller.TCMDelegate _wscDelegate;
    private static readonly WebServiceCaller _wsCaller = new WebServiceCaller();

    static void Main(string[] args)
    {
        _wscDelegate = _wsCaller.TimeConsumingMethod;

        MakeWSCallAsync();

        Console.WriteLine("Enter Q to quit");
        while (Console.ReadLine().ToUpper().Trim()!="Q"){}
    }

    public static void MakeWSCallAsync()
    {
        _wscDelegate.BeginInvoke(OnWSCallComplete, null);
    }

    public static void OnWSCallComplete(IAsyncResult ar)
    {
        Console.WriteLine("Result {0}", _wscDelegate.EndInvoke(ar));

        MakeWSCallAsync();
    }
}

class WebServiceCaller
{
    public delegate int TCMDelegate();

    public int TimeConsumingMethod()
    {
        try
        {
            // Simulates a method running for 1 minute
            Thread.Sleep(1000);
            return 1;
        }
        catch (ThreadAbortException e)
        {
            return -1;
        }
    }
}

No blocking (well, the console thread is blocking on ReadLine()) and no windows kernal mode sync objects (AutoResetEvent) which are expensive.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.