简体   繁体   中英

Forced cancellation of async wrapped sync task

I have code which calls an external lib synchronous operation, which can take a very long time to finish. I can't rewrite this lib, and there is not a method to stop the operation. Is there any solution to stop this task after some timeout?

I have tried this code, but it does not work not as I expected. It awaits until the calculation is not completed.

How can I solve this task?

 private static async Task<ResultData> GetResultAsync(string fileName)
    {
        var timeoutSource = new CancellationTokenSource(new TimeSpan(0, 5, 0)); 
        try
        {
            return await Task.Run(() =>
            {
                var result = ExternLib.Calculate(fileName);
                if (result == null)
                {
                    throw new CalculationException(fileName);
                }
                return result;
            },
                timeoutSource.Token
            ).ConfigureAwait(false);
        }
        catch (AggregateException e)
        {
            SomeCode(e);
        }
        catch (OperationCanceledException e)
        {
            SomeCode2(e);
        }
        catch (Exception e)
        {
            SomeCode3(e);
        }
        return await Task.FromResult<ResultData>(null).ConfigureAwait(false);
    }

Create two tasks, one which does the work, and one which acts as a timer:

var workTask = Task.Run(() => // etc );
var timerTask = Task.Delay(TimeSpan.FromMinutes(10));

The wait for either task to complete:

var completedTask = Task.WaitAny(new[] { workTask, timerTask });

Then, if completedTask is the timer task, your timeout has expired, and you can take appropriate action: whether or not you can stop the long running task depends on how it's structured, but you do know you can stop waiting for it.

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