views:

132

answers:

2

I have a multi-threaded application in C# which tries to write to a TextBox in a Windows.Forms created by another thread.

As threads cannot modify what has not been created by them, I was using InvokeRequired as shown on the code below, to solve this problem.

public delegate void MessageDelegate(Communication message);
void agent_MessageReceived(Communication message)
{
   if (InvokeRequired)
   {
       BeginInvoke(new MessageDelegate(agent_MessageReceived), new object[] { message });
   }
   else
   {
      TextBox1.Text += message.Body;
   }
}

Now I need to do the same for a TextBox in an ASP.NET app, but apparently neither InvokeRequired nor BeginInvoke exist for TextBox in a Web.UI. What can I do?

+2  A: 

I think that you don't need this on Web UI. Each client receives its own TextBox and the WebServer does not reuse the TextBox for more than one request. Do I miss something here?

Ikaso
So are you saying that in Web.UI if thread one make a TextBox, thread two can modify it directly?
Ali
No. What I say is that when you develop on the Web there is no situation that 2 threads modify the same TextBox at the same time.
Ikaso
OK, I got what you mean, but what I am wondering is firstly on a Web app, can one thread modify a control made by another thread directly and not necessarily in a same time, as that cannot be done on a Windows app, and if yes, how?
Ali
On a Windows app the only thread that can modify UI is the UI thread since UI classes are not thread safe. Maybe this can happen on the client-side of a web application. But I am not a specialist in developing on the client-side.
Ikaso
A: 

If you're trying to do what I think, then it's not possible. If your event handler is being called by some background process on the server then how could you possibly update a text box? Which text box would you be updating? The text boxes you are trying to update are all on the client's web browser, not your server.

Anyhow, the answer to your question is that there is no InvokeRequired or Invoke method because in ASP.NET controls cannot be accessed across threads. Only a thread currently processing a web request can access the elements of the page being served.

You'll need to rethink your approach. You can't really do things in a web application the same way that you would a desktop application.

Josh Einstein
Thanks, that was very helpful. I know now that the approach need to be changed. Do you have any suggestion?
Ali
Sorry for the late reply. I didn't notice your comment. One possible alternative if you have a long-running operation is to use asynchronous page processing in ASP.NET. http://msdn.microsoft.com/en-us/magazine/cc163725.aspx or you could use something like an Ajax polling mechanism.
Josh Einstein