如何计算百分比并将其报告给后台工作人员

本文关键字:报告 工作人员 后台 百分比 何计算 计算 | 更新日期: 2023-09-27 18:33:27

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

我有这个方法:

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;
}

在后台工作和进度更改事件

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();
}

如何计算百分比并将其报告给后台工作人员

你需要在 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>