【问题标题】:Prevent from another process to access the same ftp stream防止另一个进程访问相同的 ftp 流
【发布时间】:2015-01-29 02:31:05
【问题描述】:

我试图弄清楚如何在我仍在从另一个进程/计算机写入 ftp 的同时阻止对同一 ftp 流的访问。

这是我尝试的代码:

    internal static bool WriteFileToServer(string urlToWriteOn, string strAllContent)
    {
        Uri ServerUri = new Uri(urlToWriteOn);
        if (ServerUri.Scheme != Uri.UriSchemeFtp)
            return false;

        // Get the object used to communicate with the server.
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ServerUri);
        request.Method = WebRequestMethods.Ftp.UploadFile;
        byte[] ContentsToWrite = Encoding.UTF8.GetBytes(strAllContent);
        request.ContentLength = ContentsToWrite.Length;

        request.Credentials = new NetworkCredential(UserID, Password);
        request.UsePassive = false;
        request.KeepAlive = false;
        Stream requestStream = request.GetRequestStream();
        requestStream.Write(ContentsToWrite, 0, ContentsToWrite.Length);

        System.Threading.Thread.Sleep(10000);

        requestStream.Close();
        FtpWebResponse response = (FtpWebResponse)request.GetResponse();

        response.Close();
        return true;
    }

我创建了 2 个线程同时访问该函数,并且它们在写入 ftp 后(在关闭部分之前)都停止在睡眠行中。 为了测试,第一个线程写了 10,000 行,第二个线程写了 500 行。

事实上,第一个线程正在 ftp 上创建新文件并写入所有行,然后另一个线程来重写前 500 行(第一个线程的其他 9,500 行保持存在) 我希望第二个线程抛出异常,但事实并非如此。 如果写入 ftp 的代码来自同一个应用程序,我正在解决问题,但它将由 2 台不同的计算机写入,我不希望另一台计算机同时写入 ftp 文件。

【问题讨论】:

  • 你知道Thread synchronization - lock or SyncLock keywords吗?
  • 您的标题“防止另一个线程访问相同的 ftp 流” 可能具有误导性,因为它们可能 “相同FTP 流”,同一台计算机或其他。在本地,每个线程都创建自己的流。对于多计算机场景,我会认为在 FTP 服务器端处理?
  • AVD - 正如我在问题中所写 - 锁定解决方案对我没有帮助,因为该应用程序将从 2 台计算机上运行,​​我无法以这种方式同步访问。
  • Micky Duncan - 我明白你在说什么 - 你对这个标题有什么建议? “防止从另一个线程访问同一个ftp文件c#”比较好?
  • TVC - 请检查我的编辑,如果您认为这不是您想要的,请随时恢复。

标签: c# ftp stream


【解决方案1】:

我不相信您希望从客户端完成。我的猜测是,更好的方法是写入“随机”文件名或带有“.inprogress”扩展名或类似名称的文件,然后在上传完成后适当地重命名文件。

【讨论】:

    猜你喜欢
    • 2022-09-24
    • 2013-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-05
    • 2017-10-08
    • 1970-01-01
    相关资源
    最近更新 更多