jjzjj

c# - 如何在长时间的服务器进程中显示信息丰富的实时进度数据

coder 2024-05-25 原文

我有一个很长的过程可能需要 1 小时。

这个过程由许多步骤组成,年复一年。我的主要问题是:

如何在此过程中向最终用户提供信息丰富的实时进度,而不仅仅是一个虚拟加载栏。

            int index = Convert.ToInt32(e.CommandArgument);
            bool done = false;
            int res = -1;
            int fromVal = int.Parse(gv_balance.Rows[index].Cells[0].Text);
            int toVal = int.Parse(gv_balance.Rows[index].Cells[1].Text);
            int finMonth = 1;
            int finYear = 0;
            int EndServ = 0;
            int calcYear = int.Parse(gv_balance.Rows[index].Cells[2].Text);
            int total;
            total = ((toVal - fromVal) + 1);
            string msg = string.Empty;

            int confirm = Balance.GetConfirmState(calcYear);
            if (confirm == 0)
            {
                RadProgressContext progress = RadProgressContext.Current;
                progress.Speed = "N/A";

                finYear = fromVal;

                for (int i = fromVal; i <= toVal; i++)
                {
                    decimal ratio;
                    //Load New Employees
                    if (toVal - fromVal > 0)
                    {
                        ratio = ((decimal)toVal - i) / (toVal - fromVal) * 100;
                    }
                    else
                    {
                        ratio = ((decimal)toVal - i) / 1 * 100;
                    }
                    progress.PrimaryTotal = total;
                    progress.PrimaryValue = total;
                    progress.PrimaryPercent = 100;

                    progress.SecondaryTotal = 100; // total;
                    progress.SecondaryValue = ratio;//i ;
                    progress.SecondaryPercent = ratio; //i;


                    progress.CurrentOperationText = "Step " + i.ToString();
                    if (!Response.IsClientConnected)
                    {
                        //Cancel button was clicked or the browser was closed, so stop processing
                        break;
                    }

                    progress.TimeEstimated = (toVal - i) * 100;
                    //Stall the current thread for 0.1 seconds
                    System.Threading.Thread.Sleep(100);
                    EndServ = i + 1;
                    if (i == fromVal)
                    {   
                        //--->STEP1
                        //Load intial data 
                        int intial = Balance.PrepareIntialData(calcYear);
                        //--->STEP2
                        res = Balance.CalcEndServed(calcYear, EndServ - 1, 6, 30);

                    }
                     //--->STEP3
                    int newEmps = Balance.PrepareNewEmployees(calcYear, i);

                    for (int j = 0; j < 2; j++)
                    {
                        if (j == 0)
                        {
                            finMonth = 7;
                            finYear = i;

                        }
                        else
                        {
                            finMonth = 1;
                            finYear = i + 1;
                        }
                        //--->STEP4
                        int promotion1 = Balance.PreparePromotionFirst(finYear, finMonth, calcYear);
                         //--->STEP5
                        int promotion2 = Balance.PreparePromotionSecond(finYear, finMonth, calcYear);
                         //--->STEP6
                        int appointment1 = Balance.PrepareAppointmentFirst(finYear, finMonth, calcYear);
                         //--->STEP7
                        int appointment2 = Balance.PrepareAppointmentSecond(finYear, finMonth, calcYear);

                        //--->STEP8
                        int bonus = Balance.PrepareBonus(finMonth, finYear, 0, calcYear);

                         //--->STEP9
                        int salary = Balance.PrepareSalary(finYear, finMonth, calcYear);
                     (((CheckBox)gv_balance.Rows[index].Cells[3].FindControl("chk_redirect")).Checked == true)
                        {
                           //--->STEP9
                            int acco = Balance.PrepareFinanceAccount(finYear, finMonth, calcYear);
                        }

                    }


                    //--->STEP10
                    res = Balance.CalcEndServed(calcYear, EndServ, 6, 30);
                    Balance.CalcStudy(calcYear);
                    UpdateProgressContext();
                    if (res < 0)
                    {

                        success_lb.Visible = false;
                        error_lb.Visible = true;
                        error_lb.Text = "ERROR";

                    }
                    else
                    {
                        done = true;
                        success_lb.Visible = true;
                        error_lb.Visible = false;
                        success_lb.Text = "Success";
                    }


                }
            }

例如,我想显示当前步骤: (Promotion 1) in ---> 1-2018 以及除预计时间外整个过程的百分比。

最佳答案

要使用 signalR 报告一个非常长的任务的进度,您可以这样做(这只是一个展示它如何工作的示例):

服务器部分

我们从映射 SignalR 开始。

public class Startup
{
   public void Configuration(IAppBuilder app)
   {
       // Any connection or hub wire up and configuration should go here
       app.MapSignalR();
   }
}

我们创建一个 hub 类(不要忘记安装 signalr 包):

(如果您想向所有连接的用户或特定的用户组报告进度,请查看此处:http://www.asp.net/signalr/overview/guide-to-the-api/working-with-groups)

在给定的示例中,它仅向 Start 函数的调用者报告进度。

public class MyHub : Hub
{     
    public void Start(string arg)
    {
        Task.Run(() =>
        {
            AVeryLongTask();
        });
    }

    //simulate a long task
    void AVeryLongTask()
    {
        for (int i = 0; i < 10000; i++)
        {
            Thread.Sleep(100);              
            Clients.Caller.ReportProgress("AVeryLongTask", i * 100 / 10000);
        }
    }
}

客户端部分

在 html 中你必须添加这些引用:

<!--Script references. -->
<!--Reference the jQuery library. -->
<script src="Scripts/jquery-1.6.4.min.js"></script>
<!--Reference the SignalR library. -->
<script src="/Scripts/jquery.signalR-2.0.0.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="/signalr/hubs"></script>

现在是从中心获取进度的 Js 部分:

 $(function() {
   // Declare a proxy to reference the hub.
   var hub = $.connection.myHub;
   // Create a function that the hub can call to report progress.
   hub.client.reportProgress = function(functionName, progress) {
     $('#progression').append('<li><strong>' + progress + '</strong>:&nbsp;&nbsp;' + functionName + '</li>');
   };
   // Start the connection.
   $.connection.hub.start().done(function() {
     $('#startlongprocess').click(function() {
      //start the long process
       hub.server.start("arg");
       alert("started");
     });
   });
 });

进度和开始按钮的 html 容器:

<div class="container">    
   <input type="button" id="startlongprocess" value="Send" />
   <ul id="progression"></ul>
</div>

如果您需要更多解释,请随时询问。

(我的例子是基于signalr团队的http://www.asp.net/signalr/overview/getting-started/tutorial-getting-started-with-signalr)

关于c# - 如何在长时间的服务器进程中显示信息丰富的实时进度数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37541427/

有关c# - 如何在长时间的服务器进程中显示信息丰富的实时进度数据的更多相关文章

  1. ruby - 如何在 Ruby 中顺序创建 PI - 2

    出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits

  2. ruby - 使用 ruby​​ 和 savon 的 SOAP 服务 - 2

    我正在尝试使用ruby​​和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我

  3. ruby - 具有身份验证的私有(private) Ruby Gem 服务器 - 2

    我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..

  4. ruby-on-rails - Rails 编辑表单不显示嵌套项 - 2

    我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib

  5. ruby-on-rails - Rails 常用字符串(用于通知和错误信息等) - 2

    大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje

  6. ruby - 如何在 buildr 项目中使用 Ruby 代码? - 2

    如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby​​

  7. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  8. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  9. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  10. ruby - 如何在续集中重新加载表模式? - 2

    鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende

随机推荐