如何创建可恢复的文件上传器控制台应用程序?

发布于 2024-08-16 16:22:19 字数 255 浏览 5 评论 0原文

我正在将数千个文件上传到服务器。

服务器连接中断分配,所以我需要一种方法让这个控制台应用程序能够在连接失败几秒钟等情况下恢复。

我的应用程序很简单,它只是获取 c:\uploads 文件夹中的所有文件,然后使用 Web 服务将文件上传到服务器。

所以:

foreach(文件中的字符串文件) { 上传到服务器(文件); 我

怎样才能做到这一点,以便在连接失败时能够重新恢复? (失败通常只持续几秒钟)

I am uploading thousands of files to a server.

The server connection breaks allot, so I need a way for this console application to be able to recover if the connection fails for a few seconds etc.

My application is simple, it just gets all the files in the c:\uploads folder and then uses a web service to upload the files to the server.

so:

foreach(string file in files)
{
UploadToServer(file);
}

How can I make this so it re-covers in the event of a connection failure? (failures usually last just a few seconds)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

哀由 2024-08-23 16:22:20

使用一个小辅助方法,在认输之前重试上传几次。例如:

static void UploadFile(string file) {
  for (int attempt = 0; ; ++attempt) {
    try {
      UploadToServer(file);
      return;
    }
    catch (SocketException ex) {
      if (attempt < 10 && (
          ex.SocketErrorCode == SocketError.ConnectionAborted ||
          ex.SocketErrorCode == SocketError.ConnectionReset ||
          ex.SocketErrorCode == SocketError.Disconnecting ||
          ex.SocketErrorCode == SocketError.HostDown)) {
        // Connection failed, retry
        System.Threading.Thread.Sleep(1000);
      }
      else throw;
    }
  }
}

根据需要调整异常处理代码。

Use a little helper method that retries the upload several times before throwing in the towel. For example:

static void UploadFile(string file) {
  for (int attempt = 0; ; ++attempt) {
    try {
      UploadToServer(file);
      return;
    }
    catch (SocketException ex) {
      if (attempt < 10 && (
          ex.SocketErrorCode == SocketError.ConnectionAborted ||
          ex.SocketErrorCode == SocketError.ConnectionReset ||
          ex.SocketErrorCode == SocketError.Disconnecting ||
          ex.SocketErrorCode == SocketError.HostDown)) {
        // Connection failed, retry
        System.Threading.Thread.Sleep(1000);
      }
      else throw;
    }
  }
}

Tweak the exception handling code as needed.

痕至 2024-08-23 16:22:20

如果文件上传失败,是否会抛出异常?如果有,则处理异常,并将这些文件存储在某种容器中以便稍后重试,或者您可以放置​​某种 Thread.Sleep 稍等一下然后重试。

If the files fail to upload, is there an exception that's thrown? If there is, then handle the exception, and either store those files in some kind of container for retrying later, or maybe you can put some kind of Thread.Sleep to wait a little and try again.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文