【问题标题】:My C# UploadFile method successfully uploads a file, but then my UI hangs我的 C# UploadFile 方法成功上传文件,但随后我的 UI 挂起
【发布时间】:2011-06-02 07:40:52
【问题描述】:

我有一个简单的 C# WinForms 测试应用程序。使用以下方法,当我从按钮的 Click 事件处理程序调用该方法时,我可以上传文件。唯一的问题是:我的 Windows 窗体“冻结”。我无法使用关闭按钮关闭它。我必须从 IDE(Visual C# 2010 Express 版)中结束执行。以下是两种方法:

    public void UploadFile(string FullPathFilename) {
        string filename = Path.GetFileName(FullPathFilename);

        try {

            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(_remoteHost + filename);
            request.Method = WebRequestMethods.Ftp.UploadFile;
            request.Credentials = new NetworkCredential(_remoteUser, _remotePass);

            StreamReader sourceStream = new StreamReader(FullPathFilename);
            byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());

            request.ContentLength = fileContents.Length;

            Stream requestStream = request.GetRequestStream();
            requestStream.Write(fileContents, 0, fileContents.Length);

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

            response.Close();
            requestStream.Close();
            sourceStream.Close();

        }
        catch (Exception ex) {                
            MessageBox.Show(ex.Message, "Upload error");
        }
        finally {

        }

    }

在这里调用:

    private void btnUploadTxtFile_Click(object sender, EventArgs e) {

        string username = "my_username";
        string password = "my_password";
        string host = "ftp://mywebsite.com";

        try {
            clsFTPclient client = new clsFTPclient(host + "/httpdocs/non_church/", username, password);
            client.UploadFile(Path.GetDirectoryName(Application.ExecutablePath) + "\\myTextFile.txt");
        }
        catch (Exception ex) {
            MessageBox.Show(ex.Message, "Upload problem");
        }
    }

【问题讨论】:

    标签: c# upload ftp


    【解决方案1】:

    你忘了问一个问题。我想你想知道如何避免冻结。 您实现上传的方式,它占用了整个线程相对较长的时间。这还不错,但如果该线程有其他重要任务(在本例中为 UI),那就很糟糕了。

    如果对您来说是新线程,您应该认真研究一下,因为以下解决方案只是一个简单的修复,它不是很好,但它确实有效。将 UploadFile 调用替换为

            new System.Threading.Thread(() => client.UploadFile(Path.GetDirectoryName(Application.ExecutablePath) + "\\myTextFile.txt")).Start();
    

    【讨论】:

    • 好的,当然。但说真的,请研究线程,因为如果您只使用我提供的代码,就会出现错误。
    猜你喜欢
    • 1970-01-01
    • 2012-02-26
    • 1970-01-01
    • 2014-07-22
    • 2020-09-03
    • 2013-11-12
    • 2020-08-20
    • 1970-01-01
    • 2012-05-18
    相关资源
    最近更新 更多