Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在客户端显示c.NETWeb应用程序中服务器端处理的状态_C#_Asp.net - Fatal编程技术网

C# 如何在客户端显示c.NETWeb应用程序中服务器端处理的状态

C# 如何在客户端显示c.NETWeb应用程序中服务器端处理的状态,c#,asp.net,C#,Asp.net,我有一个c.NETWeb应用程序,它解析服务器上文件夹中的所有文本文件,并将这些文件中的信息插入数据库;这种情况发生在一个按钮点击方法中,需要相当长的时间,因为文本文件非常大。 如何在调用网页的标签中显示服务器当前正在解析的文件 以下是相关的aspx代码: <asp:Label ID="Label2" runat="server"></asp:Label> <asp:Button ID="Button1" runat="server" onclick="Button

我有一个c.NETWeb应用程序,它解析服务器上文件夹中的所有文本文件,并将这些文件中的信息插入数据库;这种情况发生在一个按钮点击方法中,需要相当长的时间,因为文本文件非常大。 如何在调用网页的标签中显示服务器当前正在解析的文件

以下是相关的aspx代码:

<asp:Label ID="Label2" runat="server"></asp:Label>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Parse" />
当然,这并没有按预期工作,标签只显示上次处理的文件的名称。我理解为什么会这样,一开始只是在我的代码中写的,因为我很愚蠢,没有注意,但如果可能的话,我想克服这个问题。 提前谢谢

foreach (string currentFileName in listOfFiles)
{
    Label1.Text = "Status : Parsing file " + currentFileName;
    Thread.Sleep(1000);
    // some text files processing code
    // some database code

}

首先,您必须使用System.Threading添加;命名空间。根据这段代码,每个文件显示1秒。

我想推荐Signal。在服务器端,您可以编写一个异步进程,如

public void  WatchCurrentFile() 
{
  // start working in a new thread
  var task = Task.Factory.StartNew(() => GetFile());

  task.ContinueWith(t =>
    { Caller.updateFile(t.Result); });
}

private string GetFile()
{
  string currentFile = "";
  return currentFile;
  // Alternately update asp the label here.
}
然后在客户端,使用如下脚本

<script type="text/javascript">
  // init hub 
  var proxy = $.connection.signals;

  // declare response handler functions, the server calls these
  proxy.updateFile = function (result) {
    alert("Current file being processed: " + result);
  };

  // start the connection
  $.connection.hub.start();

  // Function for the client to call
  function WatchCurrentFile() {
    proxy.WatchCurrentFile(); 
  }
</script>

SignalR任务工厂将异步调用updateFile,updateFile会定期调用GetFile来更新您的客户端。

您可以在会话中保存文件名,并使用循环中客户端的AJAX请求加载一个简单页面。我认为这对SignalR来说可能是一个很好的机会。下面是一个如何使用进度条的示例。它可能与您需要的不完全相同,但它应该允许您使用新信息异步更新UI。为什么不使用ajax和一些.net脚本呢?
<script type="text/javascript">
  // init hub 
  var proxy = $.connection.signals;

  // declare response handler functions, the server calls these
  proxy.updateFile = function (result) {
    alert("Current file being processed: " + result);
  };

  // start the connection
  $.connection.hub.start();

  // Function for the client to call
  function WatchCurrentFile() {
    proxy.WatchCurrentFile(); 
  }
</script>