简体   繁体   中英

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#.

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.

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.

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.

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