Multiple Thread Techniques For A C# Windows Service.docx
- 文档编号:4332266
- 上传时间:2022-11-29
- 格式:DOCX
- 页数:13
- 大小:68.77KB
Multiple Thread Techniques For A C# Windows Service.docx
《Multiple Thread Techniques For A C# Windows Service.docx》由会员分享,可在线阅读,更多相关《Multiple Thread Techniques For A C# Windows Service.docx(13页珍藏版)》请在冰豆网上搜索。
MultipleThreadTechniquesForAC#WindowsService
MultipleThreadTechniquesforaC#WindowsService
byScottAllen
ABSTRACT
VisualStudio.NETallowsustogetabasicWindowsserviceupandrunningquickly.Thenextstepistogiveourservicethehigh-performancefeaturesandconfigurabilityrequiredforrealworldapplications.Inthisarticle,ScottAllendemonstrateshowtousemultithreadedtechniquesin.NETtoachievehigherthroughputandscalabilityinasampleWindowsservice.Inaddition,wecoverconfigurationoftheserviceviaanXMLfile.Inordertodemonstratethetechniquesdiscussedinthearticlewedevelopa"stockalerts"Windowsservice,whichretrievesstockquotesfromawebserviceandemailsinterestedpartieswhenastockpricemovespastaspecificthreshold.Thetopicscoveredinsidethearticlearealsoapplicabletoother.NETapplicationtypes.
ARTICLE
VisualStudio.NETallowsustogetabasicWindowsserviceupandrunningquickly.Thenextstepistogiveourservicethehigh-performancefeaturesandconfigurabilityrequiredforrealworldapplications.Thisarticledemonstrateshowtousemultithreadedtechniquesin.NETtoachievehigherthroughputandscalabilityinasampleWindowsservice.Inaddition,thearticlecoversconfigurationoftheserviceviaanXMLfile.Thetopicscoveredinsidethearticlearealsoapplicabletoother.NETapplicationtypes.FormoreinformationonthebasicsofaWindowsservice,includingrequirementsandinstallation,consultBrianPatterson'sC#articleCreatingaWindowsServiceinC#-aNetworkStatusMonitor.
InordertodemonstratethetechniquesdiscussedinthearticlewedevelopaWindowsservicetoprovide"stockalerts".Thestockalertserviceretrievesstockquotesfromawebserviceandemailsinterestedpartieswhenastockpricemovespastaspecificthreshold.
Configuration
Serviceshaveseveraloptionsavailableforstorageandretrievalofapplicationspecificconfigurationinformation.Forexample,thestockalertserviceneedstokeepalistofusernamesandemailaddresses.Eachoftheseuserswillhavealistofstocksymbolswithahighandlowpricethresholdfortheservicetowatch.Inafileproductionapplication,youprobablywanttostoreconfigurationinformationinthedatabase,butforthisarticlewewilluseanXMLconfigurationfile.Thetechniquebelowworkswellforeitherscenario.Thebasiccodeisallreadyforyoutotryoutinthedownload:
simplyopenStockAlert.slninVisualStudio.NETandfollowtheinstructionshereandinthereadme.txtfileinthedownloadtocustomizeandcreatetheserviceforyourself.
TurnXMLintoanObject
OnetechniqueforreadingandwritingXMLfromC#istouseatypedDataSet.AtypedDataSetturnsXMLelementsintoDataTableswiththeXMLattributesascolumns.TypedDataSetsalsoallowyoutoaccesstheunderlyingdatawithstronglytypedpropertiesandthehelpoftheIDE'sIntellisense.WecreateatypedDataSetbystartingwitharepresentativeXMLfile.ThestockalertserviceusesthefollowingXMLstructuretostoretheusers,symbols,andthresholds.
xmlversion="1.0"encoding="utf-8"?
>
WiththeXMLfileopenintheVisualStudioIDE,rightclickonthealerts.xmlpaneandclickon"CreateSchema".ThiscreatesanXSDschemafileasshownbelow:
Makesuretodouble-checkallofthedatatypes,asthegeneratedschemaoftendefaultsalltheattributestypedtostring.Theschemageneratorunderstandstheparent-childrelationshipbetweenauserandtheirwatchlist,andgeneratesadditionalIDcolumnsforaDataRelationtoworkcorrectly.YoucanalsogeneratetypedDataSetsfromOleDBdataproviders.
Withtheschemainplace,youcanclickon"GenerateDataSet"fromthe"Schema"menu.VisualStudiosavesclassesforthetypedDataSetinasourcecodefileunderneaththeXSDfile.Select"ShowAllFiles"inthesolutionexplorertoseetheAlerts.csfile:
ThegeneratedclassesmakeitextremelyeasytomaneuverthroughtheXML.Theusersandtheirstocksbecometableswithcollectionsofrows.Asanexample,thefollowingcodesnippetdisplaysalloftheuserswatchingthestocksymbolTOY.
Alertsalerts=newAlerts();
alerts.ReadXml(XML_FILE_PATH);
Alerts.WatchRow[]watches;
watches=(Alerts.WatchRow[])alerts.Watch.Select("SYMBOL='TOY'");
for(inti=0;i { Alerts.UserRowuser=watches[i].UserRow; Console.WriteLine("User{0}High: {1}Low: {2}", user.Name,watches[i].Hi,watches[i].Lo); }´ Multithreading Ournextstepistoconcentrateonretrievingquotesandsendingnotifications.Thequickestimplementationistosimplyloopthroughthedatasetperiodicallyandcomparethequotestotheuserthresholds.Thequickimplementationcouldtakethefollowingcodeandplaceitinsidealoop. StockQuote.StockQuoteWebServicequoteService= newStockQuote.StockQuoteWebService(); for(inti=0;i { Alerts.WatchRow[]watches=alerts.User[i].GetWatchRows(); for(intj=0;j { doublequote; stringstock=watches[j].Symbol; quote=quoteService.GetQuote(stock); if(quote { //sendnotificationanddeletewatchrecord } } } Thread.Sleep(WAITTIME); Thecodeshownabovecancompletethebasictask,butthereareafewmorerequirementsforourservice: ∙TheserviceneedstotakeadvantageofadditionalCPUsonmultipleprocessormachinesandrunwebservicerequestsconcurrently. ∙Theserviceshouldretrievequotesatregularintervals(everythreeminutes). Theserequirementsgiveusascalableanddependableservicefortheusers.TosatisfytherequirementswedigintotheSystem.Threadingnamespacetoaddadditionalcapabilitiestoourservice. ServiceStart TheOnStartmethodiswheretheservicebeginstowork. protectedoverridevoidOnStart(string[]args) { alerts=LoadAlerts(); eventFinished=newAutoResetEvent(false); timer=newTimer(newTimerCallback(OnTick),null,WAIT_TIME,0); } TheservicelaunchesbyloadingtheuserpreferencesintothetypedDataSet(describedearlier)andcreatinganewAutoResetEvent(describedlater).Theservicetheninitializesatimertobegintheprocessofcheckingstockquoteseverythreeminutes.Thesepreferencesdonotchangeduringthelifetimeoftheapplication.Ifyouhaveauserinterfaceprovidedtochangeandupdatethestockalertsconfiguration,theservicewouldneedtoreloadtheDataSeteachtimethetimerfires. TimerQueues ItisimportanttorealizethetimerisnottheTimerclassfromSystem.Windows.Forms.Asmentionedinthedocumentation,theformsbasedtimerworksbestinapplicationswithWindowsandUImessagepumps,andthusisnotagoodmatchforourservice.OurtimerisalightweightresourcebuiltonthenewtimerqueueAPIsinWindows2000andresidesintheSystem.Threadingnamespace. TheBeta2documentationforSystem.Threading.Timerisstillsparse,butyoucanpickupmanyoftherequireddetailsfromtheWin32APIreferencefortimerqueues(ThefirstparameterisaTimerCallbackdelegatewiththemethodtoinvokewhenthetimerexpires.Thesecondparameterisoftypeobjectandallowsthecallertopassstateinformationtotheeventhandler. ThethirdandfourthparameterstotheTimerconstructoraredueTimeandperiod.ThedueTimespecifieshowmanymillisecondstocountbeforethetimerinvokesthecallbackfunction.Theperiodparameter(alsospecifiedinmilliseconds)createsareoccurringtimer. AfterthetimercountsoffWAIT_TIME(dueTime)milliseconds,thetimerfirestheOnTickeventandstops.IfinsteadwepassWAIT_TIMEastheperiodparameter,thetimerwouldfireOnTickandautomaticallyresetitselftocountdownagain. ItistemptingtocreateaperiodictimerandblindlyhavethetimercontinuetoinvoketheOnTickmethod.However,a"oneshot"timeristhesaferalternativeinthissituation.Consideracasewherewehaveaslowwebserviceandalargenumberofquotestoretrieve.IfwedonotfinishretrievingallofourquotesbeforethenextOnTickinvocation,therequestsbegintooverlapandeventuallywemightbogdownourservicewiththreadsandwebservicerequests.Aswewillseenext,theservicetriestoretrievequotesasclosetothespecifiedintervalaspossiblewithoutallowingalogjamtooccur. OnTick OncethetimerfiresOnTicktheheavyworkbegins. protectedvoidOnTick(objectstate) { longnextTime=0; try { DateTimestart=DateTime.Now; Hashtablesymbols=GetUniqueSymbols(); nRequests=symbols.Count; if(nRequests>0) { QueueGetQuotes(symbols); eventFinished.WaitOne(); if(alerts.HasChanges()) { alerts.AcceptChanges(); alerts.WriteXml(CONFIG_FILE); } TimeSpanelapsed=DateTime.Now-start; nextTime=WAIT_TIME-(long)elapsed.TotalMilliseconds; if(nextTime<0) { nextTime=0; } } } catch(Exceptione) { EventLog.WriteEntry(e.Message,EventLogEntryType.Error); } finally { timer=newTimer(newTimerCallback(OnTick),null,nextTime,0); } } Thefirststepistomarkthestarttime.WeneedtocalculatetheelapsedtimeforprocessingandstartanewtimerbeforethemethodexitstokeeptheOnTickthreeminutesapart.Thenewtimeriscreatedinsideafinallyblocktoensure
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- Multiple Thread Techniques For C# Windows Service
链接地址:https://www.bdocx.com/doc/4332266.html