Regarding implementation/usage of Background Worker - backgroundworker

Ok, I've poked around and can't find a suitable answer to my question. I have a rather complicated code base that uses a Timer to initiate the creation of background worker to transmit something on regular intervals.
I am running into an issue when it calls ReportProgress:
"This operation has already had OperationCompleted called on it and further calls are illegal."
Stack Trace:
at System.ComponentModel.AsyncOperation.VerifyNotCompleted()
at System.ComponentModel.AsyncOperation.Post(SendOrPostCallback d, Object arg)
at System.ComponentModel.BackgroundWorker.ReportProgress(Int32 percentProgress, Object userState)
at NAME.TX.Work(Object sender, DoWorkEventArgs e) in file.cs:line 68
at System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs e)
at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object argument)
My question is relatively simple, the function called when the timer goes off creates a new background worker, but is it actually a new background worker?
My code (simplified because its very bulky):
//THIS IS THE FUNCTION CALLED BY TIMER
public void TransmitMSG(MSG msg)
{
//Initialze _tx
this.m_thread = new BackgroundWorker();
m_thread.WorkerReportsProgress = true;
//Initialize all events used by _tx
m_thread.DoWork += new DoWorkEventHandler(this.Work);
m_thread.ProgressChanged += new ProgressChangedEventHandler(this.Report);
m_thread.RunWorkerCompleted += new RunWorkerCompletedEventHandler(this.Complete);
//Run the backgroundworker
m_thread.RunWorkerAsync(msg);
}
//THIS IS THE WORK FUNCTION
public override void Work(object sender, DoWorkEventArgs e)
{
//This code is in the TX Thread
//The sender should be the a BackgroundWorker
BackgroundWorker _tx = sender as BackgroundWorker;
//Check the Argument
if (e.Argument != null && e.Argument.GetType() == typeof(MSG))
{
//Transmit the Argument Message
m_THING.Transmit((MSG)e.MSG)
//Report progress according to the result
_tx.ReportProgress(CONSTANTS.PROGRESS.SUCCESS_TX, (MSG)e.Argument);
}
}
The Work function is an override because there is a higher handling class that allows for transmit and recieve, these two inherit from the same class so I can have common ReportProgress and Close methods.

Related

Independent thread in Asp.net 4.5

protected void Button1_OnClick(object sender, EventArgs e)
{
FineTuneDB();// Long Task running in db
SendSMStoAllClients();// Using Twolio API to send sms to all client long task
lblText.Text = "Button click is completed our system threads working on your request";
}
Is this possible that on button click I can response to client and independent long task going on separately.
If you don't care about whether task is completed or not, you call FineTuneDB method like this.
Action fineTuneDB = FineTuneDB;
fineTuneDB.BeginInvoke(null, null);
Asynchronous Method Invocation
Updated:
Action<int, string> fineTuneDB = FineTuneDB;
fineTuneDB.BeginInvoke((int)Session["id"],
Session["name"].ToString(), null, null);
// Your method will be like this
public void FineTuneDB(int id, string)
{
}

ASP.NET Response.Filter

I need to create filter that replace tags <h2> in the HTML to <h3>:
My filter
public class TagsFilter:Stream
{
HttpContext qwe;
public TagsFilter(HttpContext myContext)
{
qwe = myContext;
}
public override void Write(byte[] buffer, int offset, int count)
{
string html = System.Text.Encoding.UTF8.GetString(buffer);
html = html.Replace("<h2>", "<h3>");
qwe.Response.Write(html.ToCharArray(), 0, html.ToCharArray().Length);
}
My module
public class TagsChanger : IHttpModule
{
public void Init(HttpApplication context)
{
context.Response.Filter = new TagsFilter(context.Context);
}
I get error System.Web.HttpException:In this context, the answer is not available.
Look at Rick Strahl's post about "Capturing and Transforming ASP.NET Output with Response.Filter".
Response.Filter content is chunked. So to implement a Response.Filter effectively requires only that you implement a custom stream and handle the Write() method to capture Response output as it’s written. At first blush this seems very simple – you capture the output in Write, transform it and write out the transformed content in one pass. And that indeed works for small amounts of content. But you see, the problem is that output is written in small buffer chunks (a little less than 16k it appears) rather than just a single Write() statement into the stream, which makes perfect sense for ASP.NET to stream data back to IIS in smaller chunks to minimize memory usage en route.
Unfortunately this also makes it a more difficult to implement any filtering routines since you don’t directly get access to all of the response content which is problematic especially if those filtering routines require you to look at the ENTIRE response in order to transform or capture the output as is needed for the solution the gentleman in my session asked for.
So in order to address this a slightly different approach is required that basically captures all the Write() buffers passed into a cached stream and then making the stream available only when it’s complete and ready to be flushed.
As I was thinking about the implementation I also started thinking about the few instances when I’ve used Response.Filter implementations. Each time I had to create a new Stream subclass and create my custom functionality but in the end each implementation did the same thing – capturing output and transforming it. I thought there should be an easier way to do this by creating a re-usable Stream class that can handle stream transformations that are common to Response.Filter implementations.
Rick Strahl wrote own implementation of stream filter that permits text replacing in right way.
I did a small example. I think you have to access the original stream, rather than accessing the httpContext.
public class ReplacementStream : Stream
{
private Stream stream;
private StreamWriter streamWriter;
public ReplacementStream(Stream stm)
{
stream = stm;
streamWriter = new StreamWriter(stream, System.Text.Encoding.UTF8);
}
public override void Write(byte[] buffer, int offset, int count)
{
string html = System.Text.Encoding.UTF8.GetString(buffer);
html = html.Replace("<h2>", "<h3>");
streamWriter.Write(html.ToCharArray(), 0, html.ToCharArray().Length);
streamWriter.Flush();
}
// all other necessary overrides go here ...
}
public class FilterModule : IHttpModule
{
public String ModuleName
{
// Verweis auf Name in Web.config bei Modul-Registrierung
get { return "FilterModule"; }
}
void context_BeginRequest(object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
context.Response.Filter = new ReplacementStream(context.Response.Filter);
}
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(context_BeginRequest);
}
}
Found the solution at this post on SO. Worked for me.
The problem is that you are applying the filter in the Init event, which only occurs once per application instance (it is essentially close to App_Start).
What you need to do is hook in the BeginRequest event from the Init event, and then apply the filter on BeginRequest.
public void Init(HttpApplication application)
{
application.BeginRequest += BeginRequest;
}
private void BeginRequest(object sender, EventArgs e)
{
var app = (HttpApplication)sender;
var context = app.Context;
context.Response.Filter = new TagsFilter(context);
}

Code executed infinite times in threadpool because of exception

I've heard its bad to use ThreadPool in asp.net, however I've used it for the purpose of educating myself. My goal was to determine if the Application_Error event got fired (which is handled in the Global.asax) - my answer to that is: no, it does not get triggered.
But I had observed something strange. The thread I wrote simply queued up tasks to the threadpool. The task was meant to throw errors randomly. But I observed however that I keep frequently getting the error - the number exceeds the no. of times I've queued the task. A separate concern I have is even the System.Diagnostics.Trace.WriteLine() isn't logging messages to my output window (visual studio). Why this strange behaviour?
using System;
using System.Threading;
namespace ThreadPoolDemo.Web
{
public partial class _default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Thread t = new Thread(createthreads);
t.IsBackground = true;
t.Start();
}
void createthreads()
{
Thread.Sleep(10 * 1000);
int i;
System.Diagnostics.Trace.WriteLine("Queueing items");
for (i = 0; i < 1; i++)
ThreadPool.QueueUserWorkItem(new WaitCallback(ErrorTask), null);
System.Diagnostics.Trace.WriteLine("End Queueing items");
}
void ErrorTask(object obj)
{
Random generator = new Random();
int value = generator.Next(1);
if (value == 0)
throw new Exception("Sample exception thrown");
else
System.Diagnostics.Trace.WriteLine("Processed thread");
}
}
}
There are two problems with your ErrorTask. The first is that you're initializing a new Random instance every time the method is called. The default Random constructor seeds the random number generator with the value from Environment.TickCount, which will likely be the same for consecutive threads. So you'll get the same random sequence for multiple threads.
The bigger problem, though, is that generator.Next(1) will always return 0. Random.Next(int max) generates a random number, N, such that 0 <= N < max. So your ErrorTask will throw the exception for every thread.
I have no idea how or why it would be throwing that exception more than once per call to ErrorTask. That doesn't seem possible.
I would suggest the following modification:
private Random generator = new Random();
void ErrorTask(object obj)
{
int value;
lock (generator)
{
value = generator.Next(2);
}
if (value == 0)
throw new Exception("Sample exception thrown");
else
System.Diagnostics.Trace.WriteLine("Processed thread");
}
generator now has class scope and is initialized only once. The lock is there to prevent multiple threads from trying to generate a number at the same time. Without the lock, the random number generator can get corrupted and it will start returning 0 on every call. And I changed the parameter to generator.Next to 2, so you can get numbers 0 and 1.

Example of Asynchronous page processing in ASP.net webforms (.NET 2.0)

Can someone provide me with a simple example of Asynchronous page processing in ASP.NET Webforms 2.0 (I'm using VS 2010, so new syntax like lambdas are ok)?
I have some long running requests that I don't want tying up IIS threads.
For simplicity's sake, let's say my current code looks like this:
protected void Page_Load(object sender, EventArgs e)
{
string param1 = _txtParam1.Text;
string param2 = _txtParam2.Text;
//This takes a long time (relative to a web request)
List<MyEntity> entities = _myRepository.GetEntities(param1, param2);
//Conceptually, I would like IIS to bring up a new thread here so that I can
//display the data after it has come back.
DoStuffWithEntities(entities);
}
How can I modify this code so that it is asynchronous? Let's assume that I already set async="true" in the aspx page.
EDIT
I think I figured out how to get what I'm looking for. I've put the example code in an answer here. Feel free to point out any flaws or changes that can be made.
I asked some folks on the ASP.NET team. Here's their emailed response to me, and now, to you.
All that code ends up doing is spinning up a new thread and performing delegate invocation on that thread. So now there are two threads running: the request thread and the new thread. Hence this sample actually has worse performance than the original synchronous code would have had.
See http://www.asp.net/web-forms/tutorials/aspnet-45/using-asynchronous-methods-in-aspnet-45 for a sample on how to write and consume async methods in ASP.NET.
Here is a simple example of asynchronous processing.
protected void Page_Load(object sender, EventArgs e)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc));
ThreadPool.QueueUserWorkItem(state => Dokimes_Programming_multithread_QueryWorkThead.ThreadProc2());
Debug.Write("Main thread does some work, then sleeps.");
// If you comment out the Sleep, the main thread exits before
// the thread pool task runs. The thread pool uses background
// threads, which do not keep the application running. (This
// is a simple example of a race condition.)
// Thread.Sleep(4000);
txtDebug.Text += "ended";
Debug.Write("end.");
}
// This thread procedure performs the task.
static void ThreadProc(Object stateInfo)
{
// No state object was passed to QueueUserWorkItem, so stateInfo is null.
Debug.Write(" Hello from the thread pool 1.");
}
static void ThreadProc2()
{
// No state object was passed to QueueUserWorkItem, so stateInfo is null.
Debug.Write("Hello from the thread pool 2.");
}
Other way
You can use the PageAsyncTask, see here a full example:
http://msdn.microsoft.com/en-us/library/system.web.ui.pageasynctask.aspx
Something like
clAsynCustomObject oAsynRun = new clAsynCustomObject();
PageAsyncTask asyncTask = new PageAsyncTask(oAsynRun.OnBegin, oAsynRun.OnEnd, oAsynRun.OnTimeout, null, true);
Page.RegisterAsyncTask(asyncTask);
Page.ExecuteRegisteredAsyncTasks();
I think I discovered how to do what I wanted to accomplish... though it may not be the best way, feel free to chime in.
At the time of writing there was only one answer in this thread, by Aristos. While he gave an example of executing an asynchronous request, what I wanted was a way to tell ASP.NET to execute some long running method, release the IIS thread so it can be available to service other requests, and then come back when the method finished.
Here's what I came up with, using the same (or similar) example in the question:
using System;
using System.Collections.Generic;
using System.Threading;
using System.Web.UI;
namespace WebApplication2
{
public class MyEntity
{
public string Name { get; set; }
}
public class MyRepository
{
public List<MyEntity> GetEntities(string param1, string param2)
{
Thread.Sleep(10000);
return new List<MyEntity> {new MyEntity {Name = "John Smith"}};
}
}
public partial class Default : Page
{
private readonly MyRepository _myRepository = new MyRepository();
private List<MyEntity> _myEntities;
protected void Page_Load(object sender, EventArgs e)
{
}
private void DoStuffWithEntities()
{
Response.Write("<br/><br/><b>" + _myEntities[0].Name + "</b><br/><br/>");
}
protected void _btnProcess_Click(object sender, EventArgs e)
{
AddOnPreRenderCompleteAsync(BeginExecution, EndExecution, null);
}
private void GetEntities()
{
string param1 = _txtParam1.Text;
string param2 = _txtParam2.Text;
//This takes a long time (relative to a web request)
_myEntities = _myRepository.GetEntities(param1, param2);
}
private IAsyncResult BeginExecution(object sender, EventArgs e, AsyncCallback callback, object state)
{
var t = new ThreadStart(GetEntities);
return t.BeginInvoke(callback, null);
}
private void EndExecution(IAsyncResult result)
{
//Conceptually, I would like IIS to bring up a new thread here so that I can
//display the data after it has come back.
DoStuffWithEntities();
}
}
}

What's the best way to defer actions after a request in ASP.NET?

I'm writing an ASP.NET application. When a specific kind of request is being handled, I want to schedule a method to be called in a certain number of minutes after the request is handled. The postponed method does not need to communicate with the client that made the original request, it is just intended to do some "housekeeping" work. What is the best way to do this in an ASP.NET context? (It's ok to not fire the event if the application domain dies for some reason).
In Global.asax use this to check your incoming request:
protected void Application_BeginRequest(object sender, EventArgs e)
{
CheckRequest(HttpContext.Current.Request);
}
if your request is valid, register a cache entry:
private void CheckRequest(HttpRequest request)
{
if (request)
RegisterCacheEntry();
}
private void RegisterCacheEntry()
{
if (HttpRuntime.Cache[CacheItemKey] == null)
{
HttpRuntime.Cache.Add(CacheItemKey, "your key", null,
DateTime.Now.AddSeconds(60), //change to fire in whatever time frame you require
Cache.NoSlidingExpiration,
CacheItemPriority.NotRemovable,
new CacheItemRemovedCallback(CacheItemRemovedCallback));
}
}
then process your function in the callback:
private void CacheItemRemovedCallback(string key, object value, CacheItemRemovedReason reason)
{
// execute your function
}
You could start a timer (System.Timers.Timer) from one of the application event in global.asax.cs (e.g. in Application_BeginRequest) after checking that it is required for that request.
Then, in the handler of the timer's Elapsed event, make sure that you stop the timer.
E.g. put something like this into global.asax.cs:
System.Timers.Timer _timer = null;
void Application_BeginRequest(object sender, EventArgs e)
{
// check if cleanup must be initiated
bool mustInitCleanup = RequestRequiresCleanup();
if ((_timer == null) && mustInitCleanup)
{
_timer = new System.Timers.Timer(5000);
_timer.Elapsed += new System.Timers.ElapsedEventHandler(_timer_Elapsed);
_timer.Start();
}
}
void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
_timer.Stop();
_timer = null;
// do cleanup task
}
Simply create a new thread to do the housekeeping work and at its beginning have it sleep for however long you want the server to wait before doing the action.
For example, somewhere in that specific request you want to call DoSomething:
aNewThread = new Thread(Foo);
aNewThread.Start();
public void Foo()
{
Thread.Sleep(5000);
DoSomething();
}

Resources