C# 取消已上载的WebClient FTP上载

C# 取消已上载的WebClient FTP上载,c#,ftp,webclient,C#,Ftp,Webclient,有可能做到这一点吗 WebClient client; using (WebClient client = new WebClient()) { client.UploadProgressChanged += new UploadProgressChangedEventHandler(client_UploadProgressChanged); client.UploadFileCompleted += new UploadFileCompletedEventHandler(client

有可能做到这一点吗

WebClient client;
using (WebClient client = new WebClient())
{
  client.UploadProgressChanged += new UploadProgressChangedEventHandler(client_UploadProgressChanged);
  client.UploadFileCompleted += new UploadFileCompletedEventHandler(client_UploadFileCompleted);

  //Start the upload
  client.UploadFileAsync(new Uri("/targetfile.jpg"), @"c:\sourcefile.jpg");
}

private void client_UploadFileCompleted(object sender, UploadFileCompletedEventArgs e)
{
  //upload finished
}

private void client_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
{
  if (e.ProgressPercentage == 60)
  {
    //Cancel the upload
    client.CancelAsync();
  }

  //update progressbar
}
当我尝试用CancelAsync()取消上传时,我发现我的应用程序终止了(没有异常或错误…只是在我从IDE运行它时关闭了)。但是文件继续上传到FTP站点(我可以看到它监视FTP站点)

旁注。。。当我将它作为编译后的应用程序运行时,它也会崩溃,没有任何类型的错误,但检查应用程序下的系统日志时,我会得到一个.Net运行时错误

Application: MyUploader.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.Net.WebException
Stack:
   at System.Net.FtpDataStream.System.Net.ICloseEx.CloseEx(System.Net.CloseExState)
   at System.Net.FtpDataStream.Dispose(Boolean)
   at System.IO.Stream.Close()
   at System.Net.WebClient+UploadBitsState.Close()
   at System.Net.WebClient.UploadBitsWriteCallback(System.IAsyncResult)
   at System.Net.LazyAsyncResult.Complete(IntPtr)
   at System.Net.ContextAwareResult.CompleteCallback(System.Object)
   at System.Threading.ExecutionContext.runTryCode(System.Object)
   at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode, CleanupCode, System.Object)
   at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
   at System.Net.ContextAwareResult.Complete(IntPtr)
   at System.Net.LazyAsyncResult.ProtectedInvokeCallback(System.Object, IntPtr)
   at System.Net.Sockets.BaseOverlappedAsyncResult.CompletionPortCallback(UInt32, UInt32, System.Threading.NativeOverlapped*)
   at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32, UInt32, System.Threading.NativeOverlapped*)

想法?

让我们先看看你想要实现什么。目前,您正在使用异步方法,同时在主线程上“等待”。这表示您想要实现同步还是异步行为的模糊性。通过
while
循环等待完成前者,使用
WebClient
的异步方法完成后者。把这两个概念混在一起是没有意义的,所以不管你到底为什么会出错,你都应该先解决这个问题。对不起,柯克,我对这个问题做了一些更新以澄清问题。看起来好一点吗?