2016-02-14 23 views
3

我擴展我的方法到async,但我想有可能取消用戶請求和超時時間,但WriteLineAsync不支持取消令牌的移交。我嘗試嵌套任務,但沒有奏效。有人可以支持我嗎?WriteLineAsync與取消

public async Task tapAsync(int x, int y, int timeouttime) 
{ 
    CancellationTokenSource cts; 
    cts = new CancellationTokenSource(); 
    await Task.Run(async() => 
    { 
     try 
     { 
      cts.CancelAfter(timeouttime); 
      await myWriter.WriteLineAsync("input tap " + x.ToString() + " " + y.ToString()); 
      await myWriter.FlushAsync(); 
      await Task.Delay(2000); 
     } 
     catch (OperationCanceledException) 
     { 
      Console.WriteLine("canceled"); 
     } 
    }, cts.Token); 
    cts = null; 
} 
+1

什麼是'myWriter'的類型? –

+1

您的文本流將變爲垃圾。所以不妨將它和Close()混合起來,以使地板墊鬆開,並使異步寫入失敗。 –

回答

0

至少,您不能取消WriteLineAsync本身。

你能做的最好的是操作之間取消:

public async Task TapAsync(int x, int y, int timeouttime) 
{ 
    CancellationTokenSource cts; 
    cts = new CancellationTokenSource(); 
    cts.CancelAfter(timeouttime); 
    return TapAsync(x, y, source.Token); 
    await myWriter.WriteLineAsync("input tap " + x.ToString() + " " + y.ToString()); 
    token.ThrowIfCancellationRequested(); 
    await myWriter.FlushAsync(); 
    token.ThrowIfCancellationRequested(); 
    await Task.Delay(2000, token); 
} 

爲了清晰和靈活性,我可能會拆分出來的:

public Task TapAsync(int x, int y, int timeouttime) 
{ 
    CancellationTokenSource cts; 
    cts = new CancellationTokenSource(); 
    cts.CancelAfter(timeouttime); 
    return TapAsync(x, y, source.Token); 
} 

public async Task TapAsync(int x, int y, CancellationToken token) 
{ 
    token.ThrowIfCancellationRequested(); 
    await myWriter.WriteLineAsync("input tap " + x.ToString() + " " + y.ToString()); 
    token.ThrowIfCancellationRequested(); 
    await myWriter.FlushAsync(); 
    token.ThrowIfCancellationRequested(); 
    await Task.Delay(2000, token); 
}