Sending a message to ASP.NET at the end of a thread

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 */);
    }
} 

Answers


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.


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.


Need Your Help

Compile error in ruby on rails application (error is with rails form helpers)

ruby-on-rails ruby forms

I'm writing a ruby on rails application, and am getting a compile error for the following code

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.