Click here to Skip to main content
15,892,480 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
HI All,

Iam new to asynchronous methods i made a method

Method 1
C#
public Task<ConcurrentBag<GraphData>> GetGraphData(int UserId, string currentdate)
        {
            var graphdata = new ConcurrentBag<GraphData>();

            try
            {
                TeamPerformance teamperformance = new TeamPerformance();
                graphdata =   Task.Run(() => teamperformance.GetGraphData(UserId, currentdate)).Result;

            }
            catch (Exception ex)
            {
                //All Log Here
                throw ex;
            }
            ConcurrentBag<GraphData> g = new ConcurrentBag<GraphData>(graphdata);

            return Task.FromResult(g);
        }


Method 2
C#
public Task<ConcurrentBag<GraphData>> GetGraphData(int UserId, string currentdate)
        {
            return Task.FromResult(DataAccess.DataAccess.GetGraphData(UserId, currentdate));
        }


Method 3
C#
public static ConcurrentBag<GraphData> GetGraphData(int UserId, string currentdate)
       {

           string Date1 = "";
           ConcurrentBag<GraphData> graphdata = new ConcurrentBag<GraphData>();

           List<object> newdata = new List<object>();
           var db = new CommandRunner(ConfigurationManager.ConnectionStrings["chillibooking"].ConnectionString.ToString());
           string sql = "select get_agents_graphdata(" + UserId + ",date('" + currentdate + "'))";
           var res = db.ExecuteDynamic(sql);
           foreach (var record in res)
           {

               var exactdata = record.get_agents_graphdata;

               newdata.Add(exactdata);
           }
           for (var i = 0; i < newdata.Count; i++)
           {
               GraphData graphobj = new GraphData();
               Date1 = newdata[i].ToString();
               graphobj.WeekDate1 = Date1;
               graphdata.Add(graphobj);
           }

           return graphdata;
       }



When iam accessing GetGraphData from Mvc like this
C#
[HttpPost]
        public JsonResult GetBarChartDetails(Actiontext todaysaction)
        {
            string actualdate = todaysaction.TaskText;
            int UserAdminId = Convert.ToInt32(Session["UserId"]);
            MembershipRepository.Service.ServiceRepository serviceRepository = new MembershipRepository.Service.ServiceRepository();
            var listBarChart = serviceRepository.GetGraphData(UserAdminId, actualdate);
            return Json(listBarChart, JsonRequestBehavior.AllowGet);
        }


and my ajax call from jquery
JavaScript
var sevendatescount = [0];
var today = new Date();
   var next = sevendatescount[0] + 7;
   if (sevendatescount[0] == 0) {
       $("#chart_slide_right").hide();
   }
   else {
       $("#chart_slide_right").show();
   }
   sevendatescount[0] = next;
   var nextday = (new Date(today.setDate(today.getDate() - next)));

   var first = today.getDate(); //to set first day on monday, not on sunday, first+1 :

   var actualday = (new Date(nextday.setDate(first + 7)));


JavaScript
var actualdate = actualday.toISOString().substring(0, 10);
   var model = {
       TaskText: actualdate,
   };
   var modeldata = JSON.stringify(model);


JavaScript
$.ajax({
        type: "POST",
        crossDomain: true,
        url: '../Account/GetBarChartDetails',
        cache: false,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: modeldata,

        complete: function () {

        },
        success: function (response) {
           my logic
    });


the c# code is asynchronous when i run the app in google chrome first 3 request xhr status is 200 success then the fourth request goes status is pending i dont know where iam wrong why the server c# code is not responding is i have done anything wrong in code.Please let me know.



Thanks,

AnilKumar.D
Posted
Updated 29-Sep-15 22:10pm
v4

1 solution

Well, there's a couple things here.

The first, and the one that should be addressed immediately, is that your code is wide open for SQL injection. You'll want to do some validation on todaysaction.TaskText before passing it to GetGraphData().

Now as to your issue, the main problem is that you're not actually setting things up for asynchronous operation. Yes, the Task object is used as a part of the framework, but it doesn't work in quite the way that you think it does. The nice thing about tasks is that you can pass them around. It doesn't matter what object they ultimately execute on, they will use the context of the original object (they are a reference type).

You're also not using async and await, which are the keywords that let the compiler know to expect upcoming async operations.

Also, I'm not sure which SQL access library you're using there, but it it's entirely possible that it's not being cleaned up. You might be hitting a sql connection cap (if the CommandRunner is disposable, I would wrap it with using()).

Now, all that in mind, the code is not currently configured to run async. MS has a good primer at:

https://msdn.microsoft.com/en-us/library/hh191443.aspx[^]

Assuming the MVC Action calls Method 1:
C#
// Method 1
public Task<ConcurrentBag<GraphData>> GetGraphData(int UserId, string currentdate)
{
   TeamPerformance teamperformance = new TeamPerformance();
   return teamperformance.GetGraphData(UserId, currentdate);
}


Assuming that Method 2 is teamperformance.GetGraphData() and Method 3 is DataAccess.DataAccess.GetGraphData():
C#
// Method 2
public Task<ConcurrentBag<GraphData>> GetGraphData(int UserId, string currentdate)
{
   return DataAccess.DataAccess.GetGraphData(UserId, currentdate);
}


C#
// Controller Action
[HttpPost]
public async JsonResult GetBarChartDetails(Actiontext todaysaction)
{
   ConcurrentBag&lt;GraphData&gt; listBarChart; 
   string actualdate = todaysaction.TaskText; //perform validation
   int UserAdminId = Convert.ToInt32(Session["UserId"]);
   MembershipRepository.Service.ServiceRepository serviceRepository = new MembershipRepository.Service.ServiceRepository();
   try
   {
      listBarChart = await serviceRepository.GetGraphData(UserAdminId, actualdate);
   }
   catch(ex)
   {
      // handle, return 500, log, etc
   }
   return Json(listBarChart, JsonRequestBehavior.AllowGet);
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900