C # - abort a method if it takes too long

How can I interrupt a method if it takes too long to start?

eg.

string foo = DoSomethingComplex(); 

but if DoSomethingComplex() takes too long (maybe after 20 seconds). then just set foo to "";

+3
source share
4 answers

You can create a new thread that starts your method, and then:

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

Joining returns true if the thread completed successfully before the specified time. Obviously, it would not cancel the method (perhaps it could not do it directly), but the thread - but it seems that it would accomplish what you wanted.

A simple thread code example will probably look something like this. Note. I made some assumptions about the signature with the parameter, all in a certain class, etc. For the 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); } 

using aka code in some other method in ClassFooIsIn:

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

Foo must be initialized before the use described above, so in fact you could skip foo = ""; line.

+5
source

Create a separate thread for DoSomethingComplex and wait for the operation to complete on the main thread:

  • create an instance of AutoResetEvent and pass it to the thread that will execute DoSomethingComplex;
  • use the AutoResetEvent.Set () method in DoSomethingComplex to inform the main thread of completion
  • use AutoResetEvent.WaitOne (timeout) in the main thread
  • If WaitOne returns false, use Thread.Abort () to stop the thread if it has been running for too long.
+1
source

You cannot interrupt the execution of a method. What you can do is run this method on a separate thread and interrupt the thread if it takes too long.

0
source

research on LiMex or limited execution.

0
source

Source: https://habr.com/ru/post/1415225/


All Articles