Friday, August 22, 2014

Quick Tips of debugging async applicatoin in .net 4.5

I play around with MVC music store application that i download from Microsoft. I found a weird thing that the administrator had never been able to create in the SQL Data base during automatic sample data creation.

as i set a break point to debug the process. the process just went through without any error since it is an asynchronous  process.

here is the snippet of original code from download

 await userManager.CreateAsync(user, options.DefaultAdminPassword);

the process will stop here since i had set the breakpoint. however the process will continue to execute, since there is an asynchronous process. even i try to use the try and catch block to see if  any exception had been caught. but it is no luck

              try {
                   await userManager.CreateAsync(user, options.DefaultAdminPassword);
                  

              }
                catch(Exception ex)
                {

                }


I search through the MSDN here is reference about the wait on the asynchronous process.

http://msdn.microsoft.com/en-us/library/hh194873%28v=vs.110%29.aspx

the solutions is much like the thread computing. we can use the Thread.Sleep to pause the current thread for specific time, then resume the current process. for synchronous process we use the following code to hold the current thread for 5 seconds.
Thread.Sleep(5000) 

In Asynchronous process. there is Task.Delay method to allow the user hold the asynchronous process for specific amount of time.

                    IdentityResult result= await userManager.CreateAsync(user, options.DefaultAdminPassword);
                   await Task.Delay(5000);


here is the screen shot showing me that i can catch the asynchronous call result and view the error message





No comments:

Post a Comment