Skip to main content
 首页 » 编程设计

c#之杀死与文件流一起使用的任务的正确方法是什么

2024年02月13日13xiaohuochai

我有一个将一些数据写入文件的并行任务

using (var lFileStream = File.Open(aDestinationFile, shouldResume ? FileMode.Append : FileMode.Create, FileAccess.Write)) 
{ 
    try 
    { 
        while ((lCount = lDownloadStream.Read(lBuf, 0, lBuf.Length)) > 0) 
        { 
            lFileStream.Write(lBuf, 0, lCount); 
        } 
    } 
    finally 
    { 
        lFileStream.Close(); 
    } 
} 

我通过以下方式启动任务:

Task.Factory.StartNew(() =>  
                { 
                    try 
                    { 
                        myMethod(); 
                    } 
                    catch (Exception ex) 
                    { 
                        Log.Exc(ex); 
                    } 
                } 
            , _resetEvent.Token); 

在某些情况下我必须终止任务:

_resetEvent.Cancel(false); 
try 
{ 
    _task.Dispose(); 
} 
catch 
{ 
} 

任务停止后,我开始了一项新任务,但是当我尝试访问使用过的文件时,我得到:

The process cannot access the file 'bla-bla' because it is being used by another process.

我怎样才能正确地“终止”任务?

请您参考如下方法:

当您将 CancellationToken 传递给任务时,如果 token 在任务调度程序开始任务时被取消,则所做的一切都会阻止任务启动。一旦任务已经启动,它对任务没有影响。

你需要做的是“合作取消”,你需要检查任务中运行的代码中的 token ,并让它取消它正在做的事情。最简单的方法就是将 CancellationToken 传递给方法本身,然后运行函数 ThrowIfCancellationRequested(); 并且您的程序将抛出一个 OperationCanceledException 并执行任何清理工作已设置为处理该异常。

private void myMethod(CancellationToken token) 
{ 
    using (var lFileStream = File.Open(aDestinationFile, shouldResume ? FileMode.Append : FileMode.Create, FileAccess.Write)) 
    { 
        //The try-finally was not nessessary, Dispose() will call Close() for you. 
        while ((lCount = lDownloadStream.Read(lBuf, 0, lBuf.Length)) > 0) 
        { 
            token.ThrowIfCancellationRequested(); 
            lFileStream.Write(lBuf, 0, lCount); 
        } 
    } 
} 
 
Task.Factory.StartNew(() =>  
                { 
                    try 
                    { 
                        myMethod(_resetEvent.Token); 
                    } 
                    catch (Exception ex) 
                    { 
                        //If the task was canceled we don't need to log the exception. 
                        if(!ex is OperationCanceledException) 
                            Log.Exc(ex); 
                    } 
                } 
            , _resetEvent.Token); 

为了减少重构,您可以对编写器方法执行以下操作

//All your old code can still call this method. 
public void myMethod() 
{ 
    myMethod(CancellationToken.None); //Call the overload with a empty token. 
} 
 
//New code that needs to cancel the operation can call this method. 
public void myMethod(CancellationToken token) 
{ 
     //Slightly modified old Writer code that uses the CancelationToken inside any loops or in between any long running operations that can't be interrupted. 
}