2017-02-04 317 views
-4

我正在使用异步方法。如何在Timer引发超时事件时停止执行?如何停止c#中的异步方法执行?

我的代码:

public async Task<object> Method() 
{ 
    cts = new CancellationTokenSource(); 
    try 
    { 
     timer = new System.Timers.Timer(3000); 
     timer.Start(); 
     timer.Elapsed += (sender, e) => 
     { 
      try 
      { 
       timer_Elapsed(sender, e, cts.Token, thread); 
      } 
      catch (OperationCanceledException) 
      { 
       return; 
      } 
      catch (Exception ex) 
      { 
       return; 
      } 
     }; 
     await methodAsync(cts.Token); 
     return "message"; 
    } 
    catch (OperationCanceledException) 
    { 
     return "cancelled"; 
    } 
    catch (Exception ex) 
    { 
     return ex.Message; 
    } 
} 

// Async Call 
public async Task<object> methodAsync(CancellationToken ct) 
{ 
    try 
    { 
     pdfDocument = htmlConverter.Convert("path", ""); 
    } 
    catch(Exception ex) 
    { 
     return x.Message; 
    } 
} 

// Timer event 
void timer_Elapsed(object sender, ElapsedEventArgs e, CancellationToken ct) 
{ 
    cts.Cancel(); 
    ct.ThrowIfCancellationRequested(); 
} 
+2

您似乎试图取消代码'htmlConverter.Convert(“path”,“”)''。无法取消此代码,因为取消代码必须能够响应取消令牌。所以唯一的答案是,如果你需要取消,你需要启动一个新的进程并杀死它。否则唯一安全的行为是让这段代码运行完成。 – Enigmativity

+0

我不想取消这个'pdfDocument = htmlConverter.Convert(“path”,“”);'code。 只要尝试杀死methodAsync()函数。 有什么办法吗? –

+0

'methodAsync'函数中唯一发生的事情就是调用'.Convert',所以停止一个和停止另一个是一样的。您无法安全地强制任务/线程取消。您必须能够响应取消令牌才能正常工作。 – Enigmativity

回答

0

我想你可以尝试提何时取消它。类似于

cts.CancelAfter(TimeSpan.FromMilliseconds(5000)); 

另外,您需要在被调用方法中使用取消标记。那时你会知道何时取消。

1

下面介绍如何取消任务的工作原理:

public async Task<object> Method() 
{ 
    cts = new CancellationTokenSource(); 
    await methodAsync(cts.Token); 
    return "message"; 
} 

public Task<object> methodAsync(CancellationToken ct) 
{ 
    for (var i = 0; i < 1000000; i++) 
    { 
     if (ct.IsCancellationRequested) 
     { 
      break; 
     } 
     //Do a small part of the overall task based on `i` 
    } 
    return result; 
} 

你必须在的ct.IsCancellationRequested属性的变化,知道什么时候取消任务作出回应。一个线程/任务取消另一个线程/任务没有安全的方法。

在你的情况下,你似乎试图调用一个不知道CancellationToken的方法,所以你不能安全地取消这个任务。您必须让线程/任务继续完成。