Как открыть URL / ссылку между запущенным вызовом ajax и уничтожить все запущенные вызовы ajax? - PullRequest
0 голосов
/ 04 июня 2018

Я работаю над веб-страницей, имеющей ajax-вызов к серверу и снова с сервера (контроллера) снова вызывается служба WCF (которая требует времени) для получения некоторых данных.

Внутри сервера (Контроллер) я вызвал к сервису в Parallel, используя Task и async-await.

Моя проблема: после открытия страницы с кодом для вызова контроллера и службы WCF,Я не могу перенаправить свою вкладку / страницу на другой URL, нажав на вкладку привязки в пользовательском интерфейсе.пока не получен результат вызова ajax.

КОД UI:

 $(function () {
          if (AutomationType.toLowerCase() === "desktop") {
                          $.ajax({
                              async: true,
                              url: "/" + AutomationType + "/Home/GetAllController",
                              data: { "hostName": hostname},
                              type: 'POST',
                              dataType: 'json'                              
                          }).success(function (response) {
                              debugger;
                           })
                      }
      });

Я пытался прервать вызов ajax также, как показано ниже,

 $(function() {
        $.xhrPool = [];
        $.xhrPool.abortAll = function() {
            $(this).each(function(i, jqXHR) {   //  cycle through list of recorded connection
                jqXHR.abort();  //  aborts connection
                $.xhrPool.splice(i, 1); //  removes from list by index
            });
        }
        $.ajaxSetup({
            beforeSend: function(jqXHR) { $.xhrPool.push(jqXHR); }, //  annd connection to list
            complete: function(jqXHR) {
                var i = $.xhrPool.indexOf(jqXHR);   //  get index for current connection completed
                if (i > -1) $.xhrPool.splice(i, 1); //  removes from list by index
            }
        });
    })

        // Everything below this is only for the jsFiddle demo
        $('a').click(function () {
            $.xhrPool.abortAll();
        });

Код сервера (контроллера)

   public async Task<JsonResult> GetAllController(string hostName)
        {
            string IsControllerRunning = string.Empty;
            var currentHost = string.Empty;
            var currentRunId = string.Empty;
            var currentStatus = string.Empty;
            var ipDns = string.Empty;
            Stopwatch sw = new Stopwatch(); sw.Start();
            List<List<ExecutionStepResult>> returnresultArray = new List<List<ExecutionStepResult>>();
            List<Task<IEnumerable<ExecutionStepResult>>> taskList = new List<Task<IEnumerable<ExecutionStepResult>>>();
            Debug.WriteLine("starting 1     " + sw.Elapsed);

            var resultArray = hostName.TrimEnd('^').Split('^');
            for (int i = 0; i < resultArray.Length; i++)
            {
                string host = resultArray[i];
                Task<IEnumerable<ExecutionStepResult>> task = new Task<IEnumerable<ExecutionStepResult>>(() => getServiceResultByTask(host));
                task.Start();
                taskList.Add(task);
            }
            foreach (Task<IEnumerable<ExecutionStepResult>> taskitem in taskList)
            {
                try
                {
                    Debug.WriteLine("calling  task    " + sw.Elapsed);
                    IEnumerable<ExecutionStepResult> val = await taskitem;
                    returnresultArray.Add(val.ToList());
                }
                catch (Exception ex)
                {
                      returnresultArray.Add(new List<ExecutionStepResult>() { new ExecutionStepResult() { IsError = true, ErrorMessage="true" ,CustomMessage = ex.Message.ToString() } });
                }
            }
            for (int i = 0; i < resultArray.Length; i++)
            {
                string host = resultArray[i];
                currentHost = host.Split('|').GetValue(1).ToString();
                currentStatus = host.Split('|').GetValue(2).ToString();
                currentRunId = host.Split('|').GetValue(0).ToString();
                ipDns = host.Split('|').GetValue(3).ToString();
                List<ExecutionStepResult> exeResponse = returnresultArray[i].ToList();
                if (exeResponse.Count() > 0 && (currentStatus != "3" || (currentStatus == "3" && exeResponse[i].ErrorMessage == "true")))
                    IsControllerRunning += host + "|" + exeResponse[0].CustomMessage + "^";
                else if (exeResponse.Count() > 0 && currentStatus == "3" && exeResponse[0].ErrorMessage == "false")
                    IsControllerRunning += host;
            }
            Debug.WriteLine("end      " + sw.Elapsed);
            sw.Stop();
            return Json(IsControllerRunning, JsonRequestBehavior.AllowGet);
        }

вызов службы WCF:

приватный IEnumerable getServiceResultByTask (строка hosts) {

    using (var service = new RemoteCommandClient())
    {
        try
        {
            System.Threading.Thread.Sleep(15000);
            string currentHost = hosts.Split('|').GetValue(1).ToString();
            string currentStatus = hosts.Split('|').GetValue(2).ToString();
            string currentRunId = hosts.Split('|').GetValue(0).ToString();
            string ipDns = hosts.Split('|').GetValue(3).ToString();
            IEnumerable<ExecutionStepResult> result = service.ExecuteRemoteWithRunId("CHECK_CURRENT_EXECUTION", Convert.ToInt32(currentRunId));
            return result;
        } catch (Exception ex)
        { throw ex; }
    }

}

Тем не менее, я не знаю, как открыть / перенаправить URL страницы, если на сервере выполняется вызов ajax.Я использую signalR на этой же странице.Пожалуйста, помогите.

...