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.
source share