简体   繁体   中英

Thread doesn't seem to be running in the background

I have the following code:

public class BaseControlClass : System.Web.UI.UserControl
{
    protected delegate void AsyncronousAction();
    protected virtual void FAsyncEvent() { } //Overidden on derived classes.

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
            FPerformAsyncronousTasks(FAsyncEvent);
    }

    protected virtual void FPerformAsyncronousTasks(AsyncronousAction AsyncCallback)
    {
        new Thread(delegate()
        {
            AsyncCallback();
        }).Start();
    }
}

public class DerivedControlClass : BaseClass
{
    protected override void FAsyncEvent()
    {
        //Contact web service, wait for results, add to local database.
    }
}

What I was expecting is for the page to load and the code in FAsyncEvent() in my derived class to run behind the scenes however, the page doesn't finish loading until the code in FAsyncEvent() has completed.

Am I doing something wrong with the threading here?

EDIT Strangely, I have noticed if I do a Clean -> Build then run the code, it works fine and the page finishes loading whilst the web service is being contacted. Subsequent runs though mean the page waits until the thread has finished processing.

Your code keeps the reference to the UserControl alive, which might be preventing the request from continuing. Try passing a static method to the new thread, just as a quick check and see if it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM