Derek
Derek

Reputation: 8630

ThreadPool QueueUserWorkItem Issue ASP.NET

I've found a bug in my code that I'd love a good a explanation on.

I'm using the ThreadPool.QueueUserWorkItem to perform a task in a new thread.

Originally my code looked like this :-

var url = string.Format("{0}{1}", ConfigManager.SiteUrl, CanonicalUrl);

ThreadPool.QueueUserWorkItem(state => vice.WebsiteMessageService.SendSharePropertyMessage(url, txtEmailAddress.Text));

The bug, was that when the new thread fired my method, it lost the txtEmailAddress.Text's value, and therefore the email was never sent.

To correct this I made a simple change :-

var url = string.Format("{0}{1}", ConfigManager.SiteUrl, CanonicalUrl);
string emailAddress = txtEmailAddress.Text;
ThreadPool.QueueUserWorkItem(state => Service.WebsiteMessageService.SendSharePropertyMessage(url, emailAddress));

Now, the Thread hasthe value of my local variable fine, and the email is sent.

My Question is, Why cant my thread pass the value of the text box value directly?

Upvotes: 0

Views: 193

Answers (1)

volpav
volpav

Reputation: 5128

That might very well be because the implementation of the Text property uses the view state (which, in turn, is lazily loaded) and by the time your work item is scheduled for an execution, there might be no view state to decode (as there's not HTTP context available to your work item by default).

Here's the relevant code (with the help from JustDecompile):

public virtual string Text
{
  get
  {
    string item = (string)this.ViewState["Text"];
    if (item != null)
    {
      return item;
    }

    return string.Empty;
  }
  set
  {
    this.ViewState["Text"] = value;
  }
}

Hope this helps.

Upvotes: 3

Related Questions