【问题标题】:How can i calculate percentages and report them to backgroundworker?我如何计算百分比并将其报告给后台工作人员?
【发布时间】:2016-02-05 17:10:04
【问题描述】:

现在我正在报告我正在搜索的每个文件名,它工作正常。 但现在我还想向我在设计器中的progressBar1 报告进度百分比。计算还应包括程序是否进入 while 循环。我添加了一个 counterFiles 变量,但不知道怎么做。

我有这个方法:

public List<string> FindLines(string DirName, string TextToSearch)
{
    int countFiles = 0;
    int counter = 0;
    List<string> findLines = new List<string>();
    DirectoryInfo di = new DirectoryInfo(DirName);

   if (di != null && di.Exists)
   {
        if (CheckFileForAccess(DirName) == true)
        {
            foreach (FileInfo fi in di.EnumerateFiles("*", SearchOption.AllDirectories))
            {
                if (string.Compare(fi.Extension, ".cs", true) == 0)
                {
                    countFiles++;
                   //countFiles / 
                    backgroundWorker1.ReportProgress(0, fi.Name);
                    System.Threading.Thread.Sleep(200);
                    using (StreamReader sr = fi.OpenText())
                    {
                        string s = "";
                        while ((s = sr.ReadLine()) != null)
                        {
                            if (s.Contains(TextToSearch))
                            {
                                counter++;
                                findLines.Add(s);
                            }
                        }
                    }
                }
            }
        }
    }
    return findLines;
}

在后台worker dowork 和progresschanged 事件中

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
        FindLines(@"d:\c-sharp", "string s1 = treeView1.SelectedNode.Tag as string;");
}

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    label2.Text = e.UserState.ToString();
}

【问题讨论】:

  • 你试过谷歌搜索progressbar和progressStatus后台worker吗..stackoverflow.com/questions/13874122/…
  • 我知道计算进度 * 总数 / 100 的公式问题是我如何知道代码中的总数?在您提供的链接中,用户知道文件的数量,但是我如何找到代码中的目录总数?
  • 有几个项目可以显示您正在寻找的内容,CodeProject 网站上有一个.. 谷歌搜索 C# CodeProject backgroundworker progressbar

标签: c# .net winforms


【解决方案1】:

您需要在 Jquery 中使用 AJAX 来执行此操作。

在你的cs文件中:

声明:

    public static int DownloadPercent { get; set; }

然后使用上传方法、进度改变方法、完成方法:

private void StartDownload(string DownloadSource, string SaveLocation)
    {
        try
        {
            Thread thread = new Thread(() =>
            {
                WebClient client = new WebClient();
                client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
                client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
                client.DownloadFileAsync(new Uri(DownloadSource), SaveLocation);
            });
            thread.Name = "aFieldDownload";
            thread.Start();
        }
        catch (Exception err)
        {
            DownloadPercent = 999;
        }
    }
    void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
    {
        byteHasBeenDownloaded = true;
        try
        {
            double bytesIn = double.Parse(e.BytesReceived.ToString());
            double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
            double percentage = bytesIn / totalBytes * 100;
            DownloadPercent = int.Parse(Math.Truncate(percentage).ToString());
        }
        catch (Exception err)
        {
            DownloadPercent = 999;
        }
    }
    void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
    {
        if (byteHasBeenDownloaded)
        {
            DownloadFinishTime = DateTime.Now;
            UpdateActionDuration(false);
        }
    }

然后添加此方法,您将使用 AJAX 调用该方法来更新百分比:

    [WebMethod]
    public static int GetDownloadPercentage()
    {
        return DownloadPercent;
    }

对于 JavaScript,在文档加载时使用它:

$(document).ready(function () {
    setTimeout(updateDownProgress, 100);
});

使用这个 JavaScript 函数作为更新器:

function updateDownProgress() {
$.ajax({
    type: "POST",
    url: "Home.aspx/GetDownloadPercentage",
    data: "{}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    async: true,
    success: function (msg) {
        $("#cp_MAIN_CONTENT_DownPercentage").text(msg.d + "% DOWNLOADED");
        $("#cp_MAIN_CONTENT_progressBarDown").val(msg.d);
        if (msg.d < 100) {
            setTimeout(updateDownProgress, 100);
            if (msg.d > 0) { $(".StartDownloadButton").prop("disabled", true); }
            else { $(".StartDownloadButton").prop("disabled", false); }
        }
        else if (msg.d > 100) {
            //Use for Error codes
        }
    }
});
}

最后...为您的进度条使用此 HTML:

<asp:Panel ID="pDownLoading" CssClass="loading" runat="server">
            <progress id="progressBarDown" runat="server" value="0" max="100"></progress> <asp:Label ID="DownPercentage" runat="server"></asp:Label>
        </asp:Panel>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 2010-10-25
    • 1970-01-01
    • 2022-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多