Reputation: 59
I am new to multi-threading and I am trying to call a simple alert button when a thread ends. Here is my code...please let me know what is wrong with this as it is not working.
public static void RunUpload()
{
Thread thread = new Thread(RunUploadOnThread);
thread.Start();
while(thread.IsAlive)
{
Show("Rate upload in progress.");
}
Show("Rate upload completed.");
}
Show()
is just putting the message on the webpage:
public static void Show(string message)
{
string cleanMessage = message.Replace("'", "\'");
Page page = HttpContext.Current.CurrentHandler as Page;
string script = string.Format("alert('{0}');", cleanMessage);
if (page != null &&
!page.ClientScript.IsClientScriptBlockRegistered("alert"))
{
page.ClientScript.RegisterClientScriptBlock(
page.GetType(), "alert", script, true /* addScriptTags */);
}
}
Upvotes: 0
Views: 889
Reputation: 6515
Consider what your page is doing. When the browser request comes in, it starts a new thread and loops until it has completed (but not reliably - your use of IsAlive
has a race condition, as h. alex noted). When the loop completes, it sends the data to the browser, which can show the alert box. So even though you've created a new thread, you are not achieving any parallelism. In fact, since your first thread is busy-waiting on IsAlive
, it's actually worse performance than if you had just done the work synchronously.
You need to let the initial page request complete and have the browser ask the server for updates. Typically you would return some kind of token that can be passed to a web service to get updates.
Finally, you usually don't want to explicitly allocate new threads in ASP.Net. Under load you'll get better overall performance if you use the ThreadPool
.
Upvotes: 2
Reputation: 902
You are starting the thread and then just the line below checking if it is alive.
As this property tells us if the thread has started - it is a race condition in your code. Sometime it might work, sometime not depending on if the thread scheduler started it super quickly or not.
I suggest posting a notification that the thread has started from the worker thread itself.
If you are using .NET 4+ you can use something like task parallel library, makes for nicer code.
Then you can have the notification that it finished as a continuation. Otherwise, post the notification as a line of code from the worker thread.
Upvotes: 0