2

I need to cancel task that using a long-running method from dll (MethodFromDll() in this example) Where I can call cancellationToken.ThrowIfCancellationRequested() method to cancel this Task?

tokenSource = new CancellationTokenSource();
CancellationToken cancellationToken = tokenSource.Token;        

t = Task.Factory.StartNew(() => {
try {
    ...some code
    // I need to cancel this task manually if method not answer
    // or there is no wish to wait
    MethodFromDll(); 
   ...some code
    } catch {
         ...some code
    }
}, cancellationToken);
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
SetSun
  • 41
  • 1
  • You can add a timeout task which uses the token, as in eg http://stackoverflow.com/a/11191070/43846 – stuartd Aug 25 '15 at 14:12
  • This is Scan() method of TWAIN library, I don't know 5 seс or 5 min it runs..( – SetSun Aug 25 '15 at 14:16
  • So set it to a value long enough to do any reasonable scan, and if the user indicates before then that they wish to cancel, that's where you call the `tokenSource.Cancel` method. The timeout task will see that cancellation has been requested, and complete with `IsCancelled` set to true. – stuartd Aug 25 '15 at 14:25

1 Answers1

0

Call Cancel on your CancelationTokenSource and register callback

tokenSource = new CancellationTokenSource();
CancellationToken cancellationToken = tokenSource.Token;

return Task.Factory.StartNew(() =>
{
    try
    {
        cancellationToken.Register(() =>
        {
            //call api method to stop long running method 
        });
        //...some code
    }
    catch
    {

    }
}, cancellationToken);
Artiom
  • 7,694
  • 3
  • 38
  • 45