Friday, September 5, 2014

Wow ! Background Task in Separate thread in Asp.net web form

Its unfortunate that I never used threading to that extent as most of my work involved in web platform with very little to do with threading and task parallelism. Still there are cases where this Background Task can come handy. Now it depends.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.IO;

using System.Threading;



 
 
public partial class _Default : System.Web.UI.Page



{
 
protected void Page_Load(object sender, EventArgs e)



{
 
//We started this task in separate thread which will not interfere in web page usual activity.

//We can still perform all operations and this below task will run in background.

BackgroundTest longTest = new BackgroundTest(50);

Thread backgroundThread = new Thread(new ThreadStart(longTest.RunLoop));

backgroundThread.Name = "BackgroundThread";

backgroundThread.IsBackground = true;



backgroundThread.Start();
 
Label1.Text = "end";



}
 
///


/// Non Stoppable Button click..I mean we can still perform this operation

/// independent of below background thread.

///

///

///

protected void Button1_Click(object sender, System.EventArgs e)



{
 
Response.Write("Som Button Click");



}
 
///


/// Background Thread

///

class BackgroundTest



{
 
int maxIterations;

public BackgroundTest(int maxIterations)



{
 
this.maxIterations = maxIterations;
}
 
public void RunLoop()



{
 
String threadName = Thread.CurrentThread.Name;

for (int i = 0; i < maxIterations; i++)



{
 
Thread.Sleep(25000);



}
 
System.IO.File.AppendAllText("E:/test", DateTime.Now.ToString());



}

}

}
 

No comments :