簡體   English   中英

如何在客戶端顯示ac#.NET Web應用程序中服務器端處理的狀態

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

我有這個c#.net Web應用程序,它(除其他外)解析服務器上某個文件夾中的所有文本文件,並將這些文件中的信息插入數據庫中; 這種情況發生在Button_Click方法中,並且需要相當長的時間(文本文件很大)。 我如何(如果有可能)在調用網頁的標簽中顯示服務器當前正在解析的文件?

這是相關的aspx代碼:

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

這是c#代碼背后的代碼:

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

    }
}

當然,這不能按預期工作,標簽僅顯示最后處理的文件的名稱。 我理解為什么會這樣(並且起初只是在我的代碼中編寫它是因為我很愚蠢並且沒有引起注意),但是我想克服這個問題(如果可能的話)。 提前致謝

我會像bsayegh一樣,推薦SignalR。 在服務器端,您可以編寫一個異步過程,例如

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(),而后者又會定期調用GetFile()來更新您的客戶端。

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

}

首先,您必須using System.Threading;添加using System.Threading; 命名空間。 通過此代碼,每個文件顯示1秒鍾。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM