我使用System.IO.File.Copy将文件从远程共享复制到本地系统。如果副本耗时太长,如何实现超时?
答案 0 :(得分:1)
例如,可以使用async
- await
模式以这种方式完成:
Task timeoutTask = Task.Delay(TimeSpan.FromSeconds(10));
// I use a completion source to set File.Copy thread from its own
// thread, and use it later to abort it if needed
TaskCompletionSource<Thread> copyThreadCompletionSource = new TaskCompletionSource<Thread>();
// This will await while any of both given tasks end.
await Task.WhenAny
(
timeoutTask,
Task.Factory.StartNew
(
() =>
{
// This will let main thread access this thread and force a Thread.Abort
// if the operation must be canceled due to a timeout
copyThreadCompletionSource.SetResult(Thread.CurrentThread);
File.Copy(@"C:\x.txt", @"C:\y.txt");
}
)
);
// Since timeoutTask was completed before wrapped File.Copy task you can
// consider that the operation timed out
if (timeoutTask.Status == TaskStatus.RanToCompletion)
{
// Timed out!
Thread copyThread = await copyThreadCompletionSource.Task;
copyThread.Abort();
}
您可以封装此内容,以便在需要时重复使用:
public static class Timeout
{
public static async Task<bool> ForAsync(Action operationWithTimeout, TimeSpan maxTime)
{
Contract.Requires(operationWithTimeout != null);
Task timeoutTask = Task.Delay(maxTime);
TaskCompletionSource<Thread> copyThreadCompletionSource = new TaskCompletionSource<Thread>();
// This will await while any of both given tasks end.
await Task.WhenAny
(
timeoutTask,
Task.Factory.StartNew
(
() =>
{
// This will let main thread access this thread and force a Thread.Abort
// if the operation must be canceled due to a timeout
copyThreadCompletionSource.SetResult(Thread.CurrentThread);
operationWithTimeout();
}
)
);
// Since timeoutTask was completed before wrapped File.Copy task you can
// consider that the operation timed out
if (timeoutTask.Status == TaskStatus.RanToCompletion)
{
// Timed out!
Thread copyThread = await copyThreadCompletionSource.Task;
copyThread.Abort();
return false;
}
else
{
return true;
}
}
}
在项目的某个地方,您可以这样调用上述方法:
bool success = await Timeout.ForAsync(() => File.Copy(...), TimeSpan.FromSeconds(10));
if(success)
{
// Do stuff if File.Copy didn't time out!
}
注意我使用了Thread.Abort()
而不是CancellationToken
。在您的用例中,您需要调用一个不能使用所谓的取消模式的同步方法,我相信这可能是Thread.Abort()
可能是有效选项的少数情况之一
在一天结束时,如果超时,代码将中止执行File.Copy
的线程,因此,它应该足以停止I / O操作。
答案 1 :(得分:1)
您可以实现一个简单的方法,类似于以下内容,构建在Stream.CopyToAsync()上,接受取消令牌:
static async Task Copy(string destFilePath, string sourceFilePath, int timeoutSecs)
{
var cancellationSource = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutSecs));
using (var dest = File.Create(destFilePath))
using (var src = File.OpenRead(sourceFilePath))
{
await src.CopyToAsync(dest, 81920, cancellationSource.Token);
}
}
如您所见,可以创建CancellationTokenSource(),在指定时间后自动取消。
您可以使用async的复制方法:
try
{
await Copy(@"c:\temp\test2.bin", @"c:\temp\test.bin", 60);
Console.WriteLine("finished..");
}
catch (OperationCanceledException ex)
{
Console.WriteLine("cancelled..");
}
catch (Exception ex)
{
Console.WriteLine("error..");
}
或旧方式:
var copyInProgress = Copy(@"c:\temp\test2.bin", @"c:\temp\test.bin", 60);
copyInProgress.ContinueWith(
_ => { Console.WriteLine("cancelled.."); },
TaskContinuationOptions.OnlyOnCanceled
);
copyInProgress.ContinueWith(
_ => { Console.WriteLine("finished.."); },
TaskContinuationOptions.OnlyOnRanToCompletion
);
copyInProgress.ContinueWith(
_ => { Console.WriteLine("failed.."); },
TaskContinuationOptions.OnlyOnFaulted
);
copyInProgress.Wait();
很容易改进上述代码以使用可由用户控制的第二取消令牌(通过取消按钮)。您需要使用的只是CancellationTokenSource.CreateLinkedTokenSource