0

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?

1
  • 1
    I don't understand why this has been down-voted. Looks to me like a perfectly valid question. Commented Dec 12, 2013 at 11:36

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this explains the problem perfectly.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.