Amazon Ad

Thursday, 1 May 2014

Creating Asynchronous Thread in Global.asax in MVC

Hi guys,

I was facing a problem of creating asynchronous thread in Global.asax in MVC. I was able to create a thread which runs asynchrounsly without affecting the application. Here is how how i did it in global.asax.cs file. It also requires two namespaces 1. System.Threading 2. System.Threading.Tasks, Please do add them.

Step 1: Create a async Task, here in this example its MyThread.

private async Task<int> MyThread()
        {
            while (true)
            {
                string result = await Operations();
                await Task.Delay(5000);
            }
            return 1;
        }

Step 2: Create another async Task performing all the operations.

public async Task<String> Operations()
        {
            return "Hello";
        }
Step 3: Inside Application_Start call the thread.

protected async void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            AllSync();
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
        }

Thanks
Ritesh Tandon

3 comments:

Padhu said...

Thank you Ritesh

Ritesh said...

Welcome and glad it helped.

Alex said...
This comment has been removed by a blog administrator.

Post a Comment

Comments are welcome, Please join me on my Linked In account

http://in.linkedin.com/pub/ritesh-tandon/21/644/33b

How to implement Captcha v3 in ASP.NET

 I was facing an issue of dom parsing in my website. I finally resolved it by using Google Captcha V3. Step 1: Get your keys from https:...