2

I have a jquery Ajax function

  var arr = {
                id: 1,
                run: true
            }
  $.ajax({
            url: '@Url.Action("Getdata", "Details")',
            data: { Batch: arr},
            type: "POST",
            success: function (result) {
                if (result) {
                    GenNamespace.Completed(result);
                }
            },
            error: function (result) { alert("Problem Occured"); },
        });

which calls c# async function, and on successful completion of the task i am executing some function in jquery ajax success

       public async Task<JsonResult> GetData(Batch arr)
    {
        try
        {
            var success = false;
            var t = await Task.Run(() =>
            {
            //i am Performing long running task here
             return Json(success, JsonRequestBehavior.AllowGet);
            }
            });
            return t;
          }
        catch (Exception ex)
        {
            throw ex;
        }
        return null;
    }

however this is a async function, so the value(success = false) gets returned to the jquery success even though the function is not completely executed, so how do i call the javascript function only upon completion of this task, is there a task completed notification or something which i could use here in this scenario?

9
  • 2
    Async controller actions are only asynchronous from the point of view of the asp.net thread, they are not asynchronous to the JavaScript client caller. Commented Sep 10, 2015 at 8:49
  • @BenRobinson- Yes, that's true, i wanted to know how i could use it for the advantage in this situation, Commented Sep 10, 2015 at 8:50
  • 1
    might be a silly question, but do you set success variable to true in Task.Run? Commented Sep 10, 2015 at 8:52
  • Not sure what you are trying to do, the javscript will not see a difference between and async controller action and a normal one, the reason it returns success false seems to be because you are never setting it to true. Commented Sep 10, 2015 at 8:54
  • @ieaglle- Yes, i do set in the last line of the function, but initially it would be false, but it would not wait till the function gets completed, it would start the task and return to success of jqAjax. Commented Sep 10, 2015 at 8:56

3 Answers 3

6

The next code works just as expected (and it is almost equal to yours):

    [HttpPost]
    public async Task<JsonResult> GetData()
    {
        var succ = false;
        var taskRes = await Task.Run(async () =>
       {
           await Task.Delay(10000);
           succ = true;
           return Json(succ, JsonRequestBehavior.AllowGet);
       });

        return taskRes;
    }

    $.ajax({
        url: '@Url.Action("GetData", "Home")',
        type: "POST",
        success: function (result) {
            console.log(result);
        },
        error: function (result) { alert("Problem Occured"); },
    });

After execution (10s) there's 'true' in console.

Sign up to request clarification or add additional context in comments.

Comments

2

How about something like this. I think what is happening for you is that you are calling the async task but the program will continue on and return. Untested...

UPDATE: This blocks and so removes any async benefits.

    public async Task<JsonResult> GetData(Batch arr)
    {
        try
        {
            return DoTask().Result;
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return null;
    }

    private async Task<JsonResult> DoTask()
    {
        var success = false;
        var t = await Task.Run(() =>
        {
            //i am Performing long running task here
            success = true;
            return Json(success, JsonRequestBehavior.AllowGet);
        });
        return t;
    }

If you you wanted true async between the javascript client and your API I suggest you look at SignalR.

6 Comments

@deebo- thanks for the solution, i would check this and let you know.
Result property blocks current thread so there is no point in async here.
@ieaglle- then i have completely misunderstood the concept, i would then have to read async again!
Yes sorry I should have been explicit about that in my answer. That is why I mentioned SignalR.
@deebo, SignalR allows duplex communication and it is not required here as I understood.
|
0

You are not considering the stateless HTTP connection separating the client from the server. If the websocket was kept open, we could do all sorts async behavior like lazy loading of data between the client and server (Without EF). But with IObservable and Promises, there are other ways to accomplish true end-to-end async behavior. IT all comes down to how you slice and dice.

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.