简体   繁体   中英

Is it necessary for me to join my threads in C#

I'm creating an asp.net application and I'm trying to use separate threads to allow users to upload files to a server (there seems to be a lot of conflicts when two users do this at the same time). When a user hits the page, I have a pageLoad function which handles my logic:

public void UploadFile()
{
    //code to upload a file
}


protected void Page_Load(object sender, EventArgs e)
{
    Thread t1 = new Thread(UploadFile);

    t1.Start();
    t1.Join();     
}

My question is: is it really necessary to join the thread that is created? From some of the other posts, it seems to be important to join a thread so that it isn't terminated unexpectedly.

and if there are several people running this code at once, will "t1.Join()" join the current thread that they created?

I'm creating an asp.net application and I'm trying to use separate threads to allow users to upload files to a server

It is generally unwise to kick off your own threads in ASP.Net. Such threads can be terminated unexpectedly, for example if the app domain recycles.

The code UploadFile would run entirely on the server. It's not clear what that code does, but it would not be able to start a new interaction with the user's browser.

Have a look at this Microsoft documentation that illustrates how to write code to allow a file to be uploaded to the server.

http://support.microsoft.com/kb/323246

it seems to be important to join a thread so that it isn't terminated unexpectedly

A background thread will terminate if its program terminates. It is generally advisable to have threads terminate on their own, either because their work completes or in reaction to a signal of some kind.

protected void Page_Load(object sender, EventArgs e)
{
    Thread t1 = new Thread(UploadFile);

    t1.Start();
    t1.Join();     
}

This code will still block the Page_Load event. Even though it starts a new thread, it then waits for that thread to complete before returning. If you remove Join(), the handler will return right after starting the thread t1 .

您不需要使用线程来上传文件,asp.net运行时实际上是一个多线程环境。

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