safi
safi

Reputation: 3766

thread in asp.net/c#

I want to create a thread on user_login Event or Form_load Event. In this thread i want to call a class function to execute some sql statement, and the user do not have to wait for the result or background process to be finished, he is just directed to his desired page let say my profile or what ever. I am using ASP.NET, C#.

Upvotes: 1

Views: 885

Answers (3)

bigtlb
bigtlb

Reputation: 1572

You could do this by calling your method in a thread using Thread.Start. IsBackground is false by default, which should prevent your application from stopping.

http://msdn.microsoft.com/en-us/library/7a2f3ay4.aspx

But, since most of your time will probably be spent in your database call. Why not just execute it asynchronously without a callback? On a SqlCommand that would be BeginExecuteNonQuery.

Upvotes: 0

Chris Shain
Chris Shain

Reputation: 51369

For what it is worth, this is a Bad Idea. There are a variety of ways that that IIS could terminate that background thread (IIS restart, app pool restart, etc., all of which are normal expected behavior of IIS), and the result would be that your DB transaction gets silently rolled back.

If these queries need to be reliably executed, you should either execute them in the request or send them to a windows service or other long-lived process. This doesn't mean that the user can't get feedback on the progress- the IIS request itself could be executed via an AJAX call.

Upvotes: 3

escargot agile
escargot agile

Reputation: 22389

Here are some examples of asynchronous calls in C#.

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

The choice of pattern depends on your needs. Note that in sample 5 you can provide null as the callback if you don't want any code executed when the action is done.

Upvotes: 1

Related Questions