Подтвердить что ты не робот

Индикатор выполнения для длительных вызовов сервера в ASP.Net MVC

Я просто хочу создать индикатор выполнения при длительных вызовах сервера. Я не мог создать запрос на отправку ajax контроллеру, в то время как контроллер выполняет длительную работу.

Я хочу создать дополнительное действие, чтобы получить фактическую инструкцию текущей долговременной задачи. Я попытался создать опрос в запросе ajax, после чего я смогу вернуть статус со стороны сервера и отобразить его на панели выполнения клиентской стороны. Есть идеи?

4b9b3361

Ответ 1

Правильный и простой способ сделать это с помощью SignalR. Загрузите Microsoft SignalR в https://www.nuget.org/packages/Microsoft.AspNet.SignalR/2.1.2

Создайте класс концентратора в отдельной папке в пути проекта, называемой хабами, добавьте два файла класса в папку хабов

Startup.cs

using Owin;
using Microsoft.Owin;
[assembly: OwinStartup(typeof(SignalRChat.Startup))]
namespace SignalRChat
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // Any connection or hub wire up and configuration should go here
            app.MapSignalR();
        }
    }
}

ProgressHub.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using Microsoft.AspNet.SignalR;

namespace RealTimeProgressBar
{
    public class ProgressHub : Hub
    {

        public string msg = "Initializing and Preparing...";
        public int count = 1;

        public static void SendMessage(string msg , int count)
        {
            var message = "Process completed for " + msg;
            var hubContext = GlobalHost.ConnectionManager.GetHubContext<ProgressHub>();
            hubContext.Clients.All.sendMessage(string.Format(message), count);
        }

        public void GetCountAndMessage()
        {
            Clients.Caller.sendMessage(string.Format(msg), count);
        }
    }
}

В контроллере

// assemblies
using Microsoft.AspNet.SignalR;
using RealTimeProgressBar;   


//call this method inside your working action
ProgressHub.SendMessage("initializing and preparing",  2);

В представлении

<!--The jQuery library is required and is referenced by default in _Layout.cshtml. -->
<!--Reference the SignalR library. -->
<script src="~/Scripts/jquery.signalR-2.1.2.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="~/signalr/hubs"></script>
<!--SignalR script to update the chat page and send messages.--> 
<script type="text/javascript">
  $(document).ready(function () {

    $("#progressBar").kendoProgressBar({
        min: 0,
        max: 100,
        type: "percent",
    });
});

function StartInvoicing()
{
    var progressNotifier = $.connection.progressHub;

    // client-side sendMessage function that will be called from the server-side
    progressNotifier.client.sendMessage = function (message, count) {
        // update progress
        UpdateProgress(message, count);
        //alert(message);
    };

    // establish the connection to the server and start server-side operation
    $.connection.hub.start().done(function () {
        // call the method CallLongOperation defined in the Hub
        progressNotifier.server.getCountAndMessage();
    });
}

// Update the progress bar 
function UpdateProgress(message, count) {
    var result = $("#result");
    result.html(message);
    $("#progressBar").data("kendoProgressBar").value(count);
}
</script>

Подробнее см. некоторые существующие статьи с помощью google

Ответ 2

У меня была длительная работа для этого, я дал базовую идею ниже. Используйте его в соответствии с вашими требованиями.

  • Я создал структуру аргументов прогресса ProgressArgs
  • В длинном сервисе LongRunningProcess() обновлены значения прогресса на регулярном интервале и сохранены в формате JSON в базе данных
  • Создан метод действия getProgress(), который вернет ход строки JSON с помощью ajax.
  • Созданная функция Функция Javascript getProgress(), которая когда-то запускается, будет вызывать сервер через регулярные промежутки времени для достижения прогресса, пока процесс не завершится.

Я привел пример для его реализации. Надеюсь, это может вам помочь.

Класс для структуры аргументов прогресса

public class ProgressArgs
{
    public int Completed { get; set; }
    public int Total { get; set; }
    public int Percentage { get; set; }
    public string Status { get; set; }
}

В процессе я продолжал обновлять статистику в базе данных

    public void LongRunningProcess()
    {

        ProgressArgs result = new ProgressArgs();
        result.Completed = 0;
        result.Total = userList.Count;
        foreach (var item in itemList)
        {
           //Do Some processing which u want to do

            result.Total++;
            result.Percentage = (result.Completed * 100) / result.Total;
            result.Status = "Processing";
            string strToSave = Newtonsoft.Json.JsonConvert.SerializeObject(result);
            //update the strToSave to the database somewhere.
        }

        //after completing of processing
        result.Total++;
        result.Percentage = (result.Completed * 100) / result.Total;
        result.Status = "Completed";
        string strToSave = Newtonsoft.Json.JsonConvert.SerializeObject(result);
        //update the strToSave to the database somewhere.

    }

Действие С# для получения прогресса с помощью ajax

    public string getProgress()
    {    
        string strJSON = config.GetValue("progress");  //Get stats from the database which is saved in json
        return strJSON;
    }

Код Javascript

//Ajax Get Progress function
    function getProgress() {
        var dataToSend = '';
        $.ajax({
            url: '@Url.Action("getProgress")', //Link to the action method
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: dataToSend,
            success: function (response) {
                console.log(response);
                if (response != null) {
                    data = JSON.parse(response);
                    console.log(data);
                    //update the progressbar
                    progressbar.progressbar("value", data.Percentage);
                    //When the jobalert status is completed clear the interval
                    if (data.Status == 0) {
                        setTimeout(getProgress, 800); //TImout function to call the respective function at that time
                    }
                    serviceCompleted(data); function to call after completing service
                }
            },
            error: function (xhr) {
                alert('Error: There was some error while posting question. Please try again later.');
            }
        });
    }