简体   繁体   中英

How to display on the client side the status of server side processing in a c# .NET web application

I have this c# .net web application which (amongst other things) parses all text files in a folder on the server and inserts info from these files in a database; this happens in a Button_Click method and takes quite a long time (the text files are pretty big). How can i (if at all possible) display which file the server is currently parsing in a label on the calling web page ?

here is the relevant aspx code :

<asp:Label ID="Label2" runat="server"></asp:Label>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Parse" />

and here the code behind c# code :

protected void Button1_Click(object sender, EventArgs e)
{
    string path = @"c:\myPath";       
    var listOfFiles = Directory.EnumerateFiles(path);
    foreach (string currentFileName in listOfFiles)
    {
        Label1.Text = "Status : Parsing file " + currentFileName;

        // some text files processing code
        // some database code

    }
}

Of course, this doesn't work as intended, the label only displays the name of the last processed file. I understand why this is so (and only wrote it in my code at first because i was stupid and not paying attention), but i'd like to overcome this problem (if at all possible). Thanks in advance

I would, like bsayegh, recommend SignalR. On the server side, you can code up an async process like

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

then on the client side, have a script like

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

The SignalR task factory will asynchronously call updateFile(), which in turn periodically calls GetFile() to update your client.

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

}

First you have to add using System.Threading; namespace. by this code every file show for 1 second.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM