views:

97

answers:

3
protected System.Threading.Thread m_searchthread = null;

Question: I've implemented a search algorithm, which a user can start from an ASP.NET website.

When the user clicks on Button "Start", this code is executed:

m_searchthread = new System.Threading.Thread(new System.Threading.ThreadStart(Search));
m_searchthread.IsBackground = true;
m_searchthread.Start();

Now I want to make it possible to abort the search thread. So the user presses on Button "Abort", and this code is executed:

m_searchthread.Abort();

My problem now is: the postback of the abort button resets m_searchthread to NULL...

I am aware of the fact that the thread should be aborted using a flag. The core problem is just: how to stop a thread when you loose all the variables ?

A: 

Why not store the flag in the Session or ViewState and do the check in the page load event.

James
`Thread` is not `[Serializable]` so I wouldn't recommend this approach. The day you decide to use a server farm and out-of process session storage this code won't work.
Darin Dimitrov
@Darin: Yeah seen your comment I changed my answer back to ignore storing the thread in the session.
James
@James, same remark stands true for `ViewState`.
Darin Dimitrov
+2  A: 

Any variables you want persisted between postbacks need to go into either static variables, view/session state, the ASP.NET cache, or some other form of backing store.

When you postback, you will then need to go and fetch this from whatever backing store you chose.

I'm not attempting to make any comments on how you're performing your async task.

What is happening is your thread variable is local to the page. When the postback occurs, the page life cycle completes and all references to the variable are lost. Each postback triggers a new page life cycle.

You will encounter this problem whenever you have some state residing on the server that you need to remember between postbacks. ViewState is how ASP.NET controls remember their content between postbacks without you needing to repopulate them each time.

Adam
Yea, you say it: It's not possible without static variables. Which is a very very very bad idea indeed.
Quandary
@Quandary I'm trying not to place any opinions on the use of any server state - I don't do enough ASP.NET to have worthwhile input :), so I'll take your word for it.
Adam
A: 

Don't start/stop jobs from a page because is dangerous and you have no control on tasks running and started.

I suggest you to use Quartz.NET. There is a useful answer about using it in Asp.NET: http://stackoverflow.com/questions/1356789/quartz-net-with-asp-net

onof