Skip to main content
 首页 » 编程设计

c#之如何通过Escape键正确取消并行异步IO任务

2024年02月06日14myhome

我正在学习异步等待操作并找到了一个 very useful article .

我认为本文的最后一个代码片段:

public async Task ProcessWriteMult(CancellationToken cancellationToken) 
{ 
string folder = @"tempfolder\"; 
List<Task> tasks = new List<Task>(); 
List<FileStream> sourceStreams = new List<FileStream>(); 
 
try 
{ 
    for (int index = 1; index <= 10; index++) 
    { 
        string text = "In file " + index.ToString() + "\r\n"; 
 
        string fileName = "thefile" + index.ToString("00") + ".txt"; 
        string filePath = folder + fileName; 
 
        byte[] encodedText = Encoding.Unicode.GetBytes(text); 
 
        FileStream sourceStream = new FileStream(filePath, 
            FileMode.Append, FileAccess.Write, FileShare.None, 
            bufferSize: 4096, useAsync: true); 
 
        Task theTask = sourceStream.WriteAsync(encodedText, 0, encodedText.Length); 
        sourceStreams.Add(sourceStream); 
 
        tasks.Add(theTask); 
    } 
 
    await Task.WhenAll(tasks); 
} 
 
finally 
{ 
    foreach (FileStream sourceStream in sourceStreams) 
    { 
        sourceStream.Close(); 
    } 
} 
} 

我已经尝试了一些代码来取消任务,但是,恕我直言,这些都是非常丑陋的尝试。在这次尝试中,我的程序流程等待用户按下按键,但我希望这段代码能够工作,直到用户按下 Esc 按钮,如事件:

if(Console.ReadKey().Key==System.ConsoleKey.Escape) 
    cts.Cancel(); 

如何通过 Escape 键正确取消?

更新:

我插入了这段代码:

static void Main(string[] args) 
{ 
    var cts=new CancellationTokenSource(); 
    ProcessWriteMult(cts); 
    if(Console.ReadKey().Key == System.ConsoleKey.Escape) 
        cts.Cancel(); 
} 

但是,此代码不会取消方法 ProcessWriteMult(cts)。 我做错了什么?

请您参考如下方法:

首先,不要使用async void。我不确定为什么 MSDN 示例会鼓励不良做法,但仍然不要那样做。使用 async void 意味着您的方法是“即发即忘”,它不能被异步等待,并且其中发生的任何异常都将在线程池线程上抛出。相反,请使用 async Task。

现在,.NET 4.0 引入了CancellationTokenSource 的概念,它可以帮助您合作取消。这意味着您必须监控 token 才能知道有人从“外部”请求取消。这可以按如下方式完成:

try 
{ 
    for (int index = 1; index <= 10; index++) 
    { 
        // Monitor the token, you decide where. 
        cancellationToken.ThrowIfCancellationRequested(); 
        string text = "In file " + index.ToString() + "\r\n"; 
 
        string fileName = "thefile" + index.ToString("00") + ".txt"; 
        string filePath = folder + fileName; 
 
        byte[] encodedText = Encoding.Unicode.GetBytes(text); 
 
        FileStream sourceStream = new FileStream(filePath, 
            FileMode.Append, FileAccess.Write, FileShare.None, 
            bufferSize: 4096, useAsync: true); 
 
        Task theTask = sourceStream.WriteAsync(encodedText, 0, encodedText.Length); 
        sourceStreams.Add(sourceStream); 
 
        tasks.Add(theTask); 
    } 
 
    await Task.WhenAll(tasks); 
} 

However, this code does not cancel method ProcessWriteMult(cts). What am I doing wrong?

可能是当您按下 escape 时,该方法已经执行完毕。您可以通过在特定时间间隔(比如 5 秒)等待 Task.Delay 来测试这一点,然后才监控取消 token 。