5

How can I abort the execution of a method if its taking too long to run?

e.g.

string foo = DoSomethingComplex(); 

but if DoSomethingComplex() is taking too long (20 seconds lets say). then just set foo to "";

4
  • Could you run DoSomethingComplex() as a thread? Commented Jan 22, 2011 at 15:22
  • 1
    Check this post for a bunch of interesting solutions: stackoverflow.com/questions/299198/implement-c-generic-timeout Commented Jan 22, 2011 at 15:22
  • 2
    Aborting threads isn't recommended. If possible run the thread in a separate AppDomain. Commented Jan 22, 2011 at 15:26
  • 1
    You really ought to solve this inside DoSomethingComplex(). Commented Jan 22, 2011 at 19:56

4 Answers 4

6

You can create a new thread running your method, then:

thread.Start(); bool success = thread.Join(20000); 

Join returns true if thread finished successfully before designated time. Obviously, would not abort the method (probably no way to do that directly), but the thread -- but it seems that would accomplish what you desired.

A simple threading code example probably would go something like below. Note I made some assumptions about signature with parameter, all this in some class, etc. For method:

 public string DoSomethingComplex(int param) 

and then in the same class:

public delegate void Callback(string newFoo); public void ThreadedDoSomethingComplexEnded(string newFoo) { foo = newFoo; } private static void ThreadedDoSomethingComplex(ClassFooIsIn fooObject, int param, Callback callback) { var newFoo = fooObject.DoSomethingComplex(param); callback(newFoo); } 

usage aka code in some other method in ClassFooIsIn:

var thread = new Thread(() => ThreadedDoSomethingComplex(this, param, ThreadedDoSomethingComplexEnded)); thread.Start(); if (!thread.Join(20000)) { foo = ""; } 

Foo should be initialized before above shown usage, so in reality you could possibly skip foo = ""; line.

Sign up to request clarification or add additional context in comments.

Comments

1

Create a separate thread for DoSomethingComplex and wait for completion of the operation in the main thread:

  1. create an instance of AutoResetEvent and pass it to the thread that will execute DoSomethingComplex;
  2. use AutoResetEvent.Set() method in DoSomethingComplex to tell the main thread about completion
  3. use AutoResetEvent.WaitOne(timeout) in main thread
  4. If WaitOne returned false, use Thread.Abort() method to stop the thread if it works for too long.

Comments

0

You can't abort the execution of a method. What you could do is to run this method on a separate thread and abort the thread if it takes too long.

Comments

0

research on LiMex or Limited Execution.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.