簡體   English   中英

如何在程序運行時按順序運行 C# 代碼並在視圖中顯示一些數據

[英]How run C# code in sequence and show some data in view while still program is running

我有一個在 mvc5 中運行的查詢。 我需要在屏幕上寫開始時間,然后寫一些類似加載……然后寫下運行完成的時間。 我不知道用什么來按順序寫這個,而不是一次,這是我的代碼,它在運行完成后立即編寫。

   public IActionResult GetQuery()
    {
        ViewData["Timefrom"] = DateTime.Now;
        
        var Query= _context.Order.FromSqlRaw("EXECUTE [dbo].[GetStatusReport].ToList();
        
        ViewData["Timefrom2"] = DateTime.Now;
        
        return View(Query);
    }

這是我的觀點:

 @model IEnumerable<Order>
 @{
   ViewData["Title"] = "Home Page";
 }


<tbody>
Start Time: @ViewData["Timefrom"]   //need this showup 1st before query running 
@foreach (var item in Model)        //show loading when here  
{
    <tr>
        <td width="30%">@item.OrderId</td>
        <td width="30%">@item.Name</td>
        <td width="30%">@item.Location</td>
    </tr>
}  
End Time: @ViewData["Timefrom2"]    //show this at end when done running query

您的案例非常適合稱為 WebSocket 的技術。 在 Asp.net MVC 中,您可以使用 SignalR 庫以很少的代碼行實現 WebSockets。

2021 年 10 月 15 日更新:您可以按照此答案中的示例了解 WebSocket 技術以及如何將其集成到現有的 Asp.net 應用程序中。

例如,您的頁面將如何工作:

  • 頁面從控制器動作加載。 當頁面加載時,您開始繁重的過程
  • 頁面加載后,它會連接到服務器上的特定端點(使用 WebSocket)。 使用 WebSocket 連接,服務器和頁面將能夠根據需要發送/接收數據 - 雙向! 在這種情況下,服務器將在需要時向頁面發送更新。 頁面將接收數據。 並且不必間隔使用 Ajax 拉取數據。
  • 在批量處理中(您在頁面加載時已啟動)處理數據並向 WebSocket 發送定期更新
  • 任何連接到套接字的客戶端都將獲取數據(在這種情況下,您的頁面是一個客戶端)。 您可以使用來自不同頁面的相同數據。

這是基於 SignalR 的 WebSocket 的工作原理圖(該圖像是從此處收集的,您可以在此處獲得詳細說明):

在此處輸入圖片說明

這是一個示例集線器:

using AutoMapper;
using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Hubs
{
    public class ProcessHub : Hub
    {
        private static IHubContext<ProcessHub> _hubContext;
        public static Dictionary<int, List<KeyValuePair<string, string>>> AppClientStorage = new Dictionary<int, List<KeyValuePair<string, string>>>();

        public ProcessHub(IMapper mapper, IHubContext<ProcessHub> hubContext)
        {
            _hubContext = hubContext;
        }

        public async Task<string> RegisterToSocket(int userId)
        {
            KeyValuePair<string, string> keyValuePair = new KeyValuePair<string, string>(subscriptionTypeName, Context.ConnectionId);

            AddToDictionary(userId, keyValuePair);

            return "Successfully Registered.";
        }

        public static async Task NotifyUpdatesRingAsync(int userId)
        {
            if (AppClientStorage.ContainsKey(userId))
            {
                List<KeyValuePair<string, string>> userSubscriptions = AppClientStorage[userId];

                if (userSubscriptions != null)
                {
                    List<KeyValuePair<string, string>> subscribers = userSubscriptions.ToList();

                    foreach (var subsc in subscribers)
                    {
                        string data = "10% Processed. Please wait..."
                        await _hubContext.Clients.Client(subsc.Value).SendAsync("ReceiveProcessData", data);
                    }
                }
            }
        }

        private void AddToDictionary(int userId, KeyValuePair<string, string> keyValuePair)
        {
            if (!AppClientStorage.ContainsKey(userId))
            {
                AppClientStorage.Add(userId, new List<KeyValuePair<string, string>>() { keyValuePair });
            }
            else
            {
                List<KeyValuePair<string, string>> subscriptions = AppClientStorage[userId];
                List<KeyValuePair<string, string>> connectionList = subscriptions.Where(s => s.Key.Equals(keyValuePair.Key)).ToList();

                if (!connectionList.Any(s => s.Value.Equals(keyValuePair.Value)))
                {
                    subscriptions.Add(keyValuePair);
                    AppClientStorage[userId] = subscriptions;
                }
            }
        }
        
        public override Task OnDisconnectedAsync(Exception exception)
        {
            string connectionId = Context.ConnectionId;
            return base.OnDisconnectedAsync(exception);
        }       
    }
}

然后在 CShtml - 頁面加載時連接到集線器的代碼:

<script type="text/javascript">

    var connection = new signalR.HubConnectionBuilder()
        .withUrl("/processhub")
        .withAutomaticReconnect()
        .build();

    connection.on("ReceiveProcessData", function (data) {
        // Data sent by the server from the NotifyUpdatesProcessAsync function will arrive here
        // Display the 'Data' on the page as needed
    });

    connection.start();

    function subscribe() {
        connection.invoke("RegisterToSocket", 123).then(function (data) {
            // 123 is ur user Id            
            //Display the data as needed
        }).catch(err => console.error(err.toString()));
    }

</script>

在處理數據的 Action/Service 中,只需調用 hub 方法將數據推送到客戶端,如下所示:

await ProcessHub.NotifyUpdatesProcessAsync(123);

這里 123 是將獲取數據的用戶 ID。

如果您不知道如何配置集線器並在啟動時將其連接起來,您可以按照網絡上的任何教程進行操作。 例如這里是一個.

暫無
暫無

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

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