source

ASP에서 장시간 실행 중인 서버 호출의 진행률 표시줄.순 MVC

nicesource 2023. 10. 16. 21:53
반응형

ASP에서 장시간 실행 중인 서버 호출의 진행률 표시줄.순 MVC

서버 호출을 오래 실행하면서 프로그레스 바를 만들고 싶습니다.컨트롤러가 긴 실행 작업을 수행하는 동안 컨트롤러에 ajax post 요청을 생성할 수 없습니다.

현재 장기 실행 중인 작업의 실제 설명을 얻기 위해 추가 작업을 만들고 싶습니다.ajax request에서 poll을 작성하려고 하면 서버측에서 상태를 반환하여 클라이언트측 프로그레스 바에 표시할 수 있습니다.무슨 생각 있어요?

이를 위한 적절하고 가장 쉬운 방법은 시그널R을 사용하는 것입니다.https://www.nuget.org/packages/Microsoft.AspNet.SignalR/2.1.2 에서 Microsoft SignalR을 다운로드하십시오.

허브라는 프로젝트 경로의 별도 폴더에 허브 클래스를 생성하고, 두 개의 클래스 파일을 허브 폴더에 추가합니다.

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의 도움을 받아 기존 기사를 참고하시기 바랍니다.

이를 위해 오랜 기간 서비스를 해왔고, 아래에 기본적인 아이디어를 제시했습니다.요구 사항에 따라 사용하십시오.

  1. 진행 상황에 대한 논쟁의 구조를 만들었습니다.ProgressArgs
  2. LongRunningProcess()에서 진행률 값을 일정 간격으로 업데이트하여 데이터베이스에 JSON 형식으로 저장하였습니다.
  3. Action 메소드 생성했습니다.getProgress()jax에 의해 JSON 문자열 진행률을 반환합니다.
  4. 함수 자바스크립트를 만들었습니다.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에서 진행률을 얻기 위한 C# 액션

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

자바스크립트 코드

//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.');
            }
        });
    }

언급URL : https://stackoverflow.com/questions/27313550/progress-bar-for-long-running-server-calls-in-asp-net-mvc

반응형