c# - .NET Web Service & BackgroundWorker threads -
i'm trying async stuff in webservice method. let have following api call: http://www.example.com/api.asmx
and method called getproducts().
i getproducts methods, stuff (eg. data database) before return result, want async stuff (eg. send me email).
so did.
[webmethod(description = "bal blah blah.")] public ilist<product> getproducts() { // blah blah blah .. // data db .. hi db! // var mydata = ....... // moar clbuttic blahs :) (yes, google clbuttic if don't know is) // ok .. send me email no particular reason, prove async stuff works. var myobject = new myobject(); myobject.senddataasync(); // ok, return result. return mydata; } } public class trackingcode { public void senddataasync() { var backgroundworker = new backgroundworker(); backgroundworker.dowork += backgroundworker_dowork; backgroundworker.runworkerasync(); //system.threading.thread.sleep(1000 * 20); } private void backgroundworker_dowork(object sender, doworkeventargs e) { sendemail(); } }
now, when run code email never sent. if uncomment out thread.sleep .. email sent.
so ... why background worker thread torn down? dependant on parent thread? wrong way should doing background or forked threading, in asp.net web apps?
backgroundworker
useful when need synchronize (for example) ui* thread, eg affinity reasons. in case, seem using threadpool
more adequate (and simpler). if have high volumes, producer/consumer queue may allow better throttling (so don't drown in threads) - suspect threadpool
fine here...
public void senddataasync() { threadpool.queueuserworkitem(delegate { sendemail(); }); }
also - i'm not quite sure want achieve sleeping? tie thread (not using cpu, doing no either). care elaborate? looks pausing actual web page (i.e. sleep happens on web-page thread, not e-mail thread). trying here?
*=actually, use whatever sync-context in place
Comments
Post a Comment