简体   繁体   中英

Stop Task on long running method

I have an external dll with some methods I need to call. Also, I want to be able to configure a timeout for executing these methods, in order to abort them if execution time > config timeout. I call these methods on different tasks, like this:

Parallel.ForEach(....
{
    Func<object> asyncFucntion = () => DynamicCall(method, paramList);
    IAsyncResult ar = asyncFucntion.BeginInvoke(null, null);
    if (ar.AsyncWaitHandle.WaitOne(timeout, true))
    {
        return asyncFucntion.EndInvoke(ar);
    }
    else
    {
        //HERE I NEED to stop DynamicCall. Timeout was EXCEEDED
    }
});

Now, I have the possibility to get the DynamicCall Thread id and abort it. Is there any other way around? A more light way? I can't use the Cancellation Tokes, since i can't modify the external Dll

Thanks, Alex

Aborting a thread (especially a pool thread) is a really horrible thing to do. You may consider just letting each asyncFunction call come to an end naturally, without observing its result in case of time-out. See "How do I cancel non-cancelable async operations?"

On a side note, you're using Parallel.ForEach quite inefficiently here, the operation is taking roughly two times more threads than really needed. Without Parallel.ForEach , it might look like below, which is a better version, IMO:

var tasks = methods.Select(method =>
{
    Func<object> asyncFunction = () => DynamicCall(method, paramList);

    var task = Task.Factory.FromAsync(
        (asyncCallback, state) => asyncFunction.BeginInvoke(asyncCallback, state),
        (asyncResult) => asyncFunction.EndInvoke(asyncResult), 
        null);

    return Task.WhenAny(task, Task.Delay(timeout)).Unwrap();
});

Task.WhenAll(tasks).Wait(); // or Task.WaitAll();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM