Home
%3CLINGO-SUB%20id%3D%22lingo-sub-826772%22%20slang%3D%22en-US%22%3EBackground%20threads%20in%20ASP.net%20applications%20(Part%201%20%E2%80%93%20the%20concept%20application)%3C%2FLINGO-SUB%3E%3CLINGO-BODY%20id%3D%22lingo-body-826772%22%20slang%3D%22en-US%22%3E%3CP%3EWhen%20debugging%20memory%20dumps%20from%20customers%2C%20I%20have%20come%20to%20see%2C%20quite%20often%2C%20a%20pattern%20that%20you%20should%20not%20use%20in%20your%20application%20if%20you%20don%E2%80%99t%20want%20to%20run%20into%20trouble.%20This%20pattern%20can%20be%20resumed%20in%20a%20simple%20rule%3A%20%3CSTRONG%3Ethou%20shall%20not%20create%20thy%20own%20threads%20in%20thy%20application%3C%2FSTRONG%3E!%20To%20show%20you%20what%20I%20mean%2C%20through%20a%20series%20of%20three%20blog%20articles%20I%20will%20create%20a%20simple%20application%20and%20show%20you%20what%20happens%20when%20we%20transgress%20this%20rule.%3CBR%20%2F%3E%3CBR%20%2F%3E%3C%2FP%3E%0A%3CP%3ELet%E2%80%99s%20build%20a%20simple%20ISS%20(International%20Space%20Station)%20tracker%20application.%20I%20am%20basing%20my%20sample%20on%20a%20sample%20You%20can%20see%20a%20complete%20website%20that%20plots%20the%20position%20of%20the%20ISS%20on%20the%20map%20using%20the%20same%20API%20on%20this%20website%3A%20%3CSPAN%3E%3CA%20href%3D%22https%3A%2F%2Fwheretheiss.at%2F%22%20target%3D%22_blank%22%20rel%3D%22noopener%20nofollow%20noopener%20noreferrer%20noopener%20noreferrer%22%3Ehttps%3A%2F%2Fwheretheiss.at%2F%3C%2FA%3E%3C%2FSPAN%3E.%20The%20sample%20code%20for%20the%20application%20we%20are%20about%20to%20write%2C%20can%20be%20downloaded%20from%20OneDrive%20here%3A%3C%2FP%3E%0A%3CP%3E%3CBR%20%2F%3E%3CA%20href%3D%22https%3A%2F%2Fonedrive.live.com%2F%3Fid%3D9A83CB6EACC8118C%25215695%26amp%3Bcid%3D9A83CB6EACC8118C%22%20target%3D%22_self%22%20rel%3D%22noopener%20noreferrer%20noopener%20noreferrer%22%3EBackground%20Threading%20Sample%20Applications%3C%2FA%3E%3C%2FP%3E%0A%3CP%3EWhen%20you%20start%20the%20solution%2C%20you%20should%20see%20a%20page%20that%20allows%20to%20get%20telemetry%20data%20from%20the%20space%20station%20(which%20is%20catalogued%20as%20satellite%2025544).%20Here%20is%20the%20page%20loaded%20in%20Internet%20Explorer%20and%20showing%20the%20same%20telemetry%20data%3A%3C%2FP%3E%0A%3CP%3E%3CSPAN%20class%3D%22lia-inline-image-display-wrapper%20lia-image-align-inline%22%20style%3D%22width%3A%20400px%3B%22%3E%3CIMG%20src%3D%22https%3A%2F%2Fgxcuf89792.i.lithium.com%2Ft5%2Fimage%2Fserverpage%2Fimage-id%2F128929i5D57F8824D39C611%2Fimage-size%2Fmedium%3Fv%3D1.0%26amp%3Bpx%3D400%22%20alt%3D%22clipboard_image_0.png%22%20title%3D%22clipboard_image_0.png%22%20%2F%3E%3C%2FSPAN%3E%3C%2FP%3E%0A%3CP%3ESo%20how%20does%20this%20work%3F%20The%20page%20has%20a%20button%20called%20btnGetSatelliteInfoNow%20which%2C%20when%20clicked%2C%20will%20submit%20the%20page%20and%20run%20some%20code%20behind%20to%20fetch%20certain%20telemetry%20data%20for%20satellite%2025544%2C%20which%20happens%20to%20be%20the%20International%20Space%20Station.%20The%20code%20behind%20has%20a%20click%20event%20associated%20to%20the%20button%2C%20which%20looks%20like%20this%3A%3C%2FP%3E%0A%3CPRE%20class%3D%22lia-code-sample%20language-csharp%22%3E%3CCODE%3E%20%20%20%20protected%20void%20btnGetSatelliteInfoNow_Click(object%20sender%2C%20EventArgs%20e)%0A%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20var%20satellite%20%3D%20FetchSatelliteInfo()%3B%0A%20%20%20%20%20%20%20%20lblTime.Text%20%3D%20UnixTimeStampToDateTime(satellite.timestamp).ToString()%3B%0A%20%20%20%20%20%20%20%20lblAltitude.Text%20%3D%20satellite.altitude.ToString()%3B%0A%20%20%20%20%20%20%20%20lblLatitude.Text%20%3D%20satellite.latitude.ToString()%3B%0A%20%20%20%20%20%20%20%20lblLongtitude.Text%20%3D%20satellite.longitude.ToString()%3B%0A%20%20%20%20%20%20%20%20lblVelocity.Text%20%3D%20satellite.velocity.ToString()%3B%0A%20%20%20%20%20%20%20%20pnlResults.Visible%20%3D%20true%3B%0A%20%20%20%20%7D%20%0A%3C%2FCODE%3E%3C%2FPRE%3E%0A%3CP%3EThe%20code%20will%20call%20a%20method%20called%20FetchSatelliteInfo()%2C%20here%20is%20the%20code%20for%20this%20second%20method%3A%3C%2FP%3E%0A%3CPRE%20class%3D%22lia-code-sample%20language-csharp%22%3E%3CCODE%3E%20%20%20%20private%20Satellite%20FetchSatelliteInfo()%0A%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20string%20url%20%3D%20%22%3CA%20href%3D%22https%3A%2F%2Fapi.wheretheiss.at%2Fv1%2Fsatellites%2F25544%22%20target%3D%22_blank%22%20rel%3D%22nofollow%20noopener%20noreferrer%20noopener%20noreferrer%22%3Ehttps%3A%2F%2Fapi.wheretheiss.at%2Fv1%2Fsatellites%2F25544%3C%2FA%3E%22%3B%0A%20%20%20%20%20%20%20%20var%20request%20%3D%20(HttpWebRequest)WebRequest.Create(url)%3B%0A%20%20%20%20%20%20%20%20var%20reader%20%3D%20new%20StreamReader(request.GetResponse().GetResponseStream())%3B%0A%20%20%20%20%20%20%20%20string%20content%20%3D%20reader.ReadToEnd()%3B%0A%20%20%20%20%20%20%20%20reader.Close()%3B%0A%20%20%20%20%20%20%20%20var%20satellite%20%3D%20JsonConvert.DeserializeObject(content)%3B%0A%20%20%20%20%20%20%20%20return%20satellite%3B%0A%20%20%20%20%7D%20%0A%3C%2FCODE%3E%3C%2FPRE%3E%0A%3CP%3EThe%20method%20will%20compose%20a%20request%20to%20the%20ISS%20API%20url%20%E2%80%93%20(notice%20the%20url%20contains%20the%20NORAD%20catalog%20id%20for%20the%20ISS%2C%20which%20is%2025544)%2C%20then%20sends%20the%20request%20to%20retrieve%20telemetry%20information%20as%20a%20JSON%20object.%20The%20JSON%20response%20containing%20the%20satellite%20information%20from%20ISS%20API%20should%20look%20something%20like%20this%3A%3C%2FP%3E%0A%3CPRE%20class%3D%22lia-code-sample%20language-markup%22%3E%3CCODE%3E%7B%0A%20%20%20%22name%22%3A%22iss%22%2C%0A%20%20%20%22id%22%3A25544%2C%0A%20%20%20%22latitude%22%3A42.2825687563%2C%0A%20%20%20%22longitude%22%3A18.004509864333%2C%0A%20%20%20%22altitude%22%3A424.54036183209%2C%0A%20%20%20%22velocity%22%3A27573.416280786%2C%0A%20%20%20%22visibility%22%3A%22daylight%22%2C%0A%20%20%20%22footprint%22%3A4530.4910258379%2C%0A%20%20%20%22timestamp%22%3A1566134760%2C%0A%20%20%20%22daynum%22%3A2458714.0597222%2C%0A%20%20%20%22solar_lat%22%3A13.073971650332%2C%0A%20%20%20%22solar_lon%22%3A339.48156331088%2C%0A%20%20%20%22units%22%3A%22kilometers%22%0A%7D%20%0A%3C%2FCODE%3E%3C%2FPRE%3E%0A%3CP%3EThen%20the%20code%20will%20attempt%20to%20read%20the%20response%20stream%20using%20System.IO.StreamReader%20reader%2C%20so%20it%20can%20be%20deserialized%20to%20a%20POCO%20((short%20for%20Plain%20Old%20CRL%20Object)%20class%20that%20will%20represent%20the%20ISS%E2%80%99s%20telemetry%20at%20a%20given%20time.%3CBR%20%2F%3E%3CBR%20%2F%3E%3C%2FP%3E%0A%3CP%3EHere%20is%20the%20code%20listing%3A%3C%2FP%3E%0A%3CPRE%20class%3D%22lia-code-sample%20language-csharp%22%3E%3CCODE%3E%5BJsonObject(MemberSerialization.OptIn)%5D%0Apublic%20class%20Satellite%0A%7B%0A%20%20%20%20%5BJsonProperty%5D%0A%20%20%20%20public%20string%20name%20%7B%20get%3B%20set%3B%20%7D%0A%0A%20%20%20%20%5BJsonProperty%5D%0A%20%20%20%20public%20int%20id%20%7B%20get%3B%20set%3B%20%7D%0A%0A%20%20%20%20%5BJsonProperty%5D%0A%20%20%20%20public%20double%20Latitude%20%7B%20get%3B%20set%3B%20%7D%0A%0A%20%20%20%20%5BJsonProperty%5D%0A%20%20%20%20public%20double%20Longitude%20%7B%20get%3B%20set%3B%20%7D%0A%0A%20%20%20%20%5BJsonProperty%5D%0A%20%20%20%20public%20double%20Altitude%20%7B%20get%3B%20set%3B%20%7D%0A%0A%20%20%20%20%5BJsonProperty%5D%0A%20%20%20%20public%20double%20Velocity%20%7B%20get%3B%20set%3B%20%7D%0A%0A%20%20%20%20%5BJsonProperty%5D%0A%20%20%20%20public%20string%20Visibility%20%7B%20get%3B%20set%3B%20%7D%0A%0A%20%20%20%20%5BJsonProperty%5D%0A%20%20%20%20public%20double%20Footprint%20%7B%20get%3B%20set%3B%20%7D%0A%0A%20%20%20%20%5BJsonProperty%20%5D%0A%20%20%20%20public%20double%20Timestamp%20%7B%20get%3B%20set%3B%20%7D%0A%0A%20%20%20%20%5BJsonProperty%5D%0A%20%20%20%20public%20double%20Daynum%20%7B%20get%3B%20set%3B%20%7D%0A%0A%20%20%20%20%5BJsonProperty%5D%0A%20%20%20%20public%20double%20Solarlat%20%7B%20get%3B%20set%3B%20%7D%0A%0A%20%20%20%20%5BJsonProperty%5D%0A%20%20%20%20public%20double%20Solarlon%20%7B%20get%3B%20set%3B%20%7D%0A%0A%20%20%20%20%5BJsonProperty%5D%0A%20%20%20%20public%20string%20Units%20%7B%20get%3B%20set%3B%20%7D%0A%0A%7D%0A%3C%2FCODE%3E%3C%2FPRE%3E%0A%3CP%3EThis%20class%20only%20contains%20a%20couple%20of%20properties%20that%20expose%20both%20get%20and%20set%20so%20that%20we%20can%20store%20the%20data%20related%20to%20a%20satellite%20(in%20this%20case%20the%20ISS)%20inside%20an%20instance%20of%20the%20class%20and%20modify%20it%20later%20if%20we%20need%20to.%20This%20will%20represent%20our%20Business%20Layer%20(Model).%3C%2FP%3E%0A%3CP%3E%3CBR%20%2F%3EFollowing%20the%20execution%20of%20FetchSatelliteInfo%2C%20the%20rest%20of%20the%20event%20handler%20method%20for%20the%20button%20click%20will%20just%20display%20the%20values%20of%20the%20Satellite%20object%20instance%20which%20we%20have%20retrieve%20on%20the%20page.%3C%2FP%3E%0A%3CP%3ETo%20continue%20the%20development%20of%20the%20application%2C%20we%20will%20look%20at%20how%20to%20%E2%80%98optimize%E2%80%99%20the%20code%20that%20I%20have%20proposed%20so%20far%20in%20this%20artilce.%20The%20objective%20would%20be%20to%20have%20the%20application%20load%20the%20data%20in%20the%20background%20via%20a%20thread%20that%20would%20update%20the%20telemetry%20data%20for%20the%20space%20station%20every%20X%20seconds.%3C%2FP%3E%0A%3CP%3ETo%20do%20this%2C%20what%20I%20have%20seen%20many%20of%20my%20customers%20do%2C%20is%20to%20spawn%20a%20new%20.Net%20thread%20in%20the%20background%20and%20have%20this%20thread%20run%20an%20infinite%20loop%20with%20the%20following%20pseudo-logic%3A%3C%2FP%3E%0A%3COL%3E%0A%3CLI%3EWhen%20the%20application%20loads%20up%2C%20start%20the%20background%20thread%20and%20have%20it%20execute%20the%20infinite%20loop%3C%2FLI%3E%0A%3CLI%3EOnce%20in%20the%20infinite%20loop%2C%20the%20thread%20will%20the%20telemetry%20data%20by%20making%20API%20calls%3C%2FLI%3E%0A%3CLI%3EWhen%20it%20has%20retrieved%20the%20information%20for%20the%20telemetry%20data%2C%20it%20will%20go%20to%20sleep%20for%20a%20few%20seconds.%3C%2FLI%3E%0A%3CLI%3EIt%20will%20then%20resume%20the%20loop%20from%20the%20beginning%20and%20attempt%20to%20refresh%20the%20coordinates%3C%2FLI%3E%0A%3C%2FOL%3E%0A%3CP%3ESo%20let%E2%80%99s%20look%20how%20this%20pseudo%20logic%20can%20be%20transformed%20into%20code.%20Keep%20in%20mind%20that%20I%20am%20doing%20the%20bare%20minimum%20to%20keep%20the%20application%20as%20simple%20as%20possible%20and%20focus%20on%20the%20essentials.%3C%2FP%3E%0A%3CP%3EWhen%20the%20application%20loads%20into%20the%20process%20memory%20(into%20the%20w3wp.exe%20worker%20process)%2C%20the%20Application_Start%20event%20is%20fired.%20This%20seems%20like%20a%20good%20place%20to%20add%20the%20code%20to%20create%20a%20background%20thread.%3C%2FP%3E%0A%3CP%3E%3CBR%20%2F%3EThe%20first%20method%20I%20will%20implement%20is%20located%20in%20the%20Global.asax%20file%20(but%20I%20could%20have%20implemented%20this%20inside%20another%20class%20if%20I%20had%20wanted%20to%20as%20well).%20This%20method%20is%20called%20UpdateSatelliteInfo.%20Here%20is%20the%20code%20listing%3A%3C%2FP%3E%0A%3CPRE%20class%3D%22lia-code-sample%20language-csharp%22%3E%3CCODE%3E%20%20%20%20private%20void%20UpdateSatelliteInfo()%0A%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20string%20url%20%3D%20%22%3CA%20href%3D%22https%3A%2F%2Fapi.wheretheiss.at%2Fv1%2Fsatellites%2F25544%22%20target%3D%22_blank%22%20rel%3D%22nofollow%20noopener%20noreferrer%20noopener%20noreferrer%22%3Ehttps%3A%2F%2Fapi.wheretheiss.at%2Fv1%2Fsatellites%2F25544%3C%2FA%3E%22%3B%0A%20%20%20%20%20%20%20%20Satellite%20satellite%3B%20string%20content%3B%20HttpWebRequest%20request%3B%20StreamReader%20reader%3B%0A%20%20%20%20%20%20%20%20do%0A%20%20%20%20%20%20%20%20%7B%0A%0A%20%20%20%20%20%20%20%20%20%20%20%20request%20%3D%20(HttpWebRequest)WebRequest.Create(url)%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20reader%20%3D%20new%20StreamReader(request.GetResponse().GetResponseStream())%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20content%20%3D%20reader.ReadToEnd()%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20reader.Close()%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20satellite%20%3D%20JsonConvert.DeserializeObject(content)%3B%0A%0A%20%20%20%20%20%20%20%20%20%20%20%20satellite.Time%20%3D%20UnixTimeStampToDateTime(satellite.Timestamp)%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20Application%5B%22satellite%22%5D%20%3D%20satellite%3B%0A%0A%20%20%20%20%20%20%20%20%20%20%20%20%2F%2Fsleep%20for%205%20Seconds%0A%20%20%20%20%20%20%20%20%20%20%20%20System.Threading.Thread.Sleep(5000)%3B%0A%20%20%20%20%20%20%20%20%7D%20while%20(true)%3B%0A%20%20%20%20%7D%0A%3C%2FCODE%3E%3C%2FPRE%3E%0A%3CP%3EWhat%20the%20method%20does%20is%20that%20it%20will%20update%20the%20Satellite%20Info%20(just%20to%20keep%20it%20simple%20%E2%80%93%20we%20could%20use%20something%20more%20dynamic%20afterwards)%20that%20will%20be%20refreshed%20every%20X%20seconds.%20Following%20this%20declaration%2C%20it%20will%20go%20into%20an%20infinite%20loop%2C%20represented%20by%20the%20do%7B%7D%20while(true)%20statement.%3C%2FP%3E%0A%3CP%3E%3CBR%20%2F%3EThe%20Satellite%20telemetry%20data%20will%20be%20inspected%2C%20and%20we%20will%20try%20to%20obtain%20the%20current%20position%20for%20the%20ISS%2C%20by%20making%20a%20call%20to%20the%20ISS%20API%20using%20the%20StreamReader%20object.%20With%20every%20iteration%20of%20the%20while%20loop%20we%20compose%20the%20correct%20URL%20and%20then%20we%20ask%20the%20StreamReader%20object%20to%20retrieve%20the%20JSON%20datagram%20corresponding%20to%20the%20current%20state%20of%20the%20Satellite.%3C%2FP%3E%0A%3CP%3E%3CBR%20%2F%3EOnce%20we%20have%20loaded%20the%20JSON%20content%20from%20the%20StreamReader%20inside%20the%20string%20object%2C%20the%20method%20will%20create%20a%20new%20instance%20of%20the%20Satellite%20class%20and%20populate%20its%20properties%20with%20data%20extracted%20from%20the%20JSON%20%E2%80%93%20via%20the%20%3CSTRONG%3EJsonConvert.DeserializeObject%3CSATELLITE%3E(content)%3C%2FSATELLITE%3E%3C%2FSTRONG%3Emethod%2C%20just%20like%20in%20the%20previous%20sample.%3C%2FP%3E%0A%3CP%3E%3CBR%20%2F%3ENote%20that%20we%20have%20to%20convert%20date%20time%20from%20the%20loaded%20JSON%20object%2C%20which%20is%20in%20unix%20format%20and%20which%20will%20be%20mapped%20by%20the%20JSON%20deserialization%20into%20a%20property%20of%20type%20Double%2C%20to%20an%20instance%20of%20type%20DateTime.%20To%20do%20so%2C%20I%20have%20created%20a%20method%20named%20UnixTimeStampToDateTime()%3A%3C%2FP%3E%0A%3CPRE%20class%3D%22lia-code-sample%20language-csharp%22%3E%3CCODE%3Epublic%20static%20DateTime%20UnixTimeStampToDateTime(double%20unixTimeStamp)%0A%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20%2F%2F%20Unix%20timestamp%20is%20seconds%20past%20epoch%0A%20%20%20%20%20%20%20%20System.DateTime%20dtDateTime%20%3D%20new%20DateTime(1970%2C%201%2C%201%2C%200%2C%200%2C%200%2C%200)%3B%0A%20%20%20%20%20%20%20%20dtDateTime%20%3D%20dtDateTime.AddSeconds(unixTimeStamp).ToLocalTime()%3B%0A%20%20%20%20%20%20%20%20return%20dtDateTime%3B%0A%20%20%20%20%7D%0A%3C%2FCODE%3E%3C%2FPRE%3E%0A%3CP%3EThe%20newly%20created%20instance%20of%20the%20Satellite%20object%20will%20be%20added%20to%20the%20HttpApplication%20object%2C%20an%20object%20that%20is%20available%20in%20all%20parts%20of%20the%20application%20and%20that%20can%20be%20thought%20of%20as%20a%20global%20dictionary%20of%20variables.%20(Some%20of%20you%20might%20remark%20that%20I%20could%20have%20checked%20if%20I%20already%20had%20an%20entry%20for%20the%20Satellite%20inside%20the%20Application%20object%20and%20if%20so%2C%20I%20could%20just%20have%20performed%20an%20update%20on%20the%20object%20instead%20of%20creating%20a%20new%20instance%20every%20time%2C%20and%20you%20would%20be%20right%20to%20do%20so.%20However%2C%20in%20essence%20I%20am%20trying%20to%20keep%20the%20app%20basic%2C%20and%20not%20necessarily%20optimized).%3C%2FP%3E%0A%3CP%3E%3CBR%20%2F%3EFollowing%20the%20loading%20of%20the%20Satellite%20data%2C%20the%20loop%20will%20put%20the%20thread%20to%20sleep%20for%205%20seconds.%20After%20this%2C%20the%20loop%20will%20iterate%20again%20and%20again%2C%20until%20the%20end%20of%20time%2C%20or%20the%20end%20of%20the%20process%2C%20whichever%20comes%20first.%3C%2FP%3E%0A%3CP%3E%3CBR%20%2F%3ENow%20for%20the%20interface%20to%20display%20Satellite%20data%20in%20a%20web-page.%20To%20do%20this%2C%20I%20have%20created%20a%20second%20page%20for%20the%20application%2C%20called%20AutoSatellite.aspx.%20This%20page%20contains%20a%20repeater%20control%20that%20is%20strongly%E2%80%93typed%20data-bound%20to%20an%20object%20of%20type%20Satellite%2C%20via%20the%20ItemType%20property.%20If%20you%20are%20new%20to%20strongly%20typed%20data-binding%2C%20I%20would%20suggest%20you%20have%20a%20look%20at%20my%20ASP.net%204.5%20Webforms%20video%20tutorial%3A%3C%2FP%3E%0A%3CP%3E%3CSPAN%3E%3CA%20href%3D%22http%3A%2F%2Flinqto.me%2Fn%2FASPNet45%22%20target%3D%22_blank%22%20rel%3D%22noopener%20nofollow%20noopener%20noreferrer%20noopener%20noreferrer%22%3Ehttp%3A%2F%2Flinqto.me%2Fn%2FASPNet45%3C%2FA%3E%3C%2FSPAN%3E%3C%2FP%3E%0A%3CP%3E%3CBR%20%2F%3EHere%20are%20the%20tags%20for%20the%20repeater%20control%20%E2%80%93%20note%20the%20ItemType%20tag%20that%20indicates%20the%20type%20of%20object%20that%20will%20be%20displayed%20by%20the%20control%20and%20the%20SelectMethod%20tag%20will%20indicate%20which%20method%20in%20the%20code%20behind%20is%20to%20be%20called%20to%20load%20the%20elements%20to%20display%20when%20the%20control%20is%20rendered%3A%3CBR%20%2F%3E%3CBR%20%2F%3E%3C%2FP%3E%0A%3CP%3E%3CSPAN%20class%3D%22lia-inline-image-display-wrapper%20lia-image-align-inline%22%20style%3D%22width%3A%20400px%3B%22%3E%3CIMG%20src%3D%22https%3A%2F%2Fgxcuf89792.i.lithium.com%2Ft5%2Fimage%2Fserverpage%2Fimage-id%2F128932i9EBF0DD13DF3FC5E%2Fimage-size%2Fmedium%3Fv%3D1.0%26amp%3Bpx%3D400%22%20alt%3D%22clipboard_image_0.png%22%20title%3D%22clipboard_image_0.png%22%20%2F%3E%3C%2FSPAN%3E%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CDIV%20style%3D%22float%3A%20left%3B%22%3E%0A%3CP%3EInside%20the%20repeater%20control%2C%20we%20just%20display%20a%20fieldset%20tag%20for%20the%20Satellite%20Info%2C%20and%20inside%20this%20we%20display%2C%20the%20Time%2C%20the%20Alttitude%20and%20other%20information%20via%20strongly%20typed%20data-binding.%3CBR%20%2F%3E%3CBR%20%2F%3E%3C%2FP%3E%0A%3C%2FDIV%3E%0A%3CP%3E%3CSPAN%20style%3D%22font-family%3A%20inherit%3B%22%3E%3CBR%20%2F%3EInside%20the%20repeater%20control%2C%20we%20just%20display%20a%20fieldset%20tag%20for%20the%20Satellite%20Info%2C%20and%20inside%20this%20we%20display%2C%20the%20Time%2C%20the%20Alttitude%20and%20other%20information%20via%20strongly%20typed%20data-binding.%3C%2FSPAN%3E%3C%2FP%3E%0A%3CDIV%20style%3D%22float%3A%20left%3B%22%3E%0A%3CP%3EIn%20the%20code%20behind%2C%20the%20GetSatellite()%20method%20does%20the%20loading%20of%20the%20satellite%20data%20from%20the%20Application%20object%20%E2%80%93%20here%20is%20the%20code%3A%3C%2FP%3E%0A%3CPRE%20class%3D%22lia-code-sample%20language-csharp%22%3E%3CCODE%3E%20%20%20%20%20%0A%20public%20Satellite%20GetSatellite()%0A%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20%2F%2Fget%20the%20Satellite%20from%20the%20application%20object%0A%20%20%20%20%20%20%20%20Satellite%20satellite%20%3D%20new%20Satellite()%3B%0A%20%20%20%20%20%20%20%20if%20(Application%5B%22satellite%22%5D%20!%3D%20null)%0A%20%20%20%20%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20satellite%20%3D%20(Satellite)Application%5B%22satellite%22%5D%3B%0A%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20%20%20return%20satellite%3B%0A%0A%20%20%20%20%7D%20%0A%3C%2FCODE%3E%3C%2FPRE%3E%0A%3CP%3E%3CBR%20%2F%3EThe%20method%20declares%20a%20variable%20of%20type%20Satellite%20and%20attempts%20to%20assign%20the%20satellite%20info%20from%20the%20Application%20object%20to%20the%20newly%20created%20object.%20We%20check%20if%20satellite%20info%20in%20the%20Application%20object%20is%20not%20null.%20Should%20the%20background%20thread%20not%20have%20finished%20loading%20the%20satellite%20info%20for%20the%20first%20time%20before%20we%20show%20the%20page%2C%20we%20don%E2%80%99t%20want%20to%20show%20null%20data%20and%20crash%20the%20page%2C%20hence%20the%20reason%20for%20the%20test.%20It%20ensures%20that%20the%20data%20was%20loaded%20by%20the%20background%20thread%20at%20least%20once.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EThere%20is%20also%20a%20refresh%20button%20on%20the%20page%2C%20with%20a%20Click%20event%20handler%20in%20the%20code%20behind%3A%3C%2FP%3E%0A%3CPRE%20class%3D%22lia-code-sample%20language-csharp%22%3E%3CCODE%3E%20%20%20%20protected%20void%20cmdRefresh_Click(object%20sender%2C%20EventArgs%20e)%0A%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20%2F%2Fdo%20nothing%0A%20%20%20%20%20%20%20%20rptSatellite.DataBind()%3B%0A%20%20%20%20%7D%0A%3C%2FCODE%3E%3C%2FPRE%3E%0A%3CP%3EAll%20this%20does%20is%20that%20it%20forces%20the%20repeater%20control%20to%20data-bind%20once%20again%20%E2%80%93%20and%20hence%20to%20call%20the%20GetSatellite()%20method%20and%20reload%20the%20data%20from%20the%20Application%20object.%20Note%20that%20the%20data%20will%20not%20be%20reloaded%20by%20the%20background%20thread%20when%20this%20new%20call%20to%20GetSatellite()%20comes%20in.%20It%20will%20be%20refreshed%20only%20when%20the%20background%20thread%20wakes%20up%20the%20next%20time%20around%20and%20loads%20new%20data%20from%20ISS.%3C%2FP%3E%0A%3CP%3E%3CBR%20%2F%3EYou%20can%20find%20the%20sample%20completed%20with%20this%20new%20code%20in%20my%20OneDrive%20as%20well%2C%20by%20following%20this%20link%3A%3C%2FP%3E%0A%3CP%3E%3CSPAN%3E%3CA%20href%3D%22https%3A%2F%2Fonedrive.live.com%2F%3Fid%3D9A83CB6EACC8118C%25215695%26amp%3Bcid%3D9A83CB6EACC8118C%22%20target%3D%22_blank%22%20rel%3D%22noopener%20noopener%20noreferrer%20noopener%20noreferrer%22%3Ehttps%3A%2F%2Fonedrive.live.com%2F%3Fid%3D9A83CB6EACC8118C%25215695%26amp%3Bcid%3D9A83CB6EACC8118C%3C%2FA%3E%3C%2FSPAN%3E%3C%2FP%3E%0A%3CP%3E%3CA%20href%3D%22https%3A%2F%2Ftechcommunity.microsoft.com%2Ft5%2FIIS-Support-Blog%2FBackground-threads-in-ASP-net-applications-Part-2-threading-side%2Fba-p%2F826929%22%20target%3D%22_self%22%3EIn%20the%20next%20installment%3C%2FA%3E%2C%20I%20will%20discuss%20the%20problems%20with%20this%20kind%20of%20pattern%20and%20why%20it%20is%20not%20recommended%20you%20make%20use%20of%20it%20in%20your%20ASP.net%20applications.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3Ewritten%20by%3A%20%3CA%20href%3D%22http%3A%2F%2Fwww.linqto.me%2Fabout%2Fpcociuba%22%20target%3D%22_self%22%20rel%3D%22nofollow%20noopener%20noreferrer%20noopener%20noreferrer%22%3EPaul%20Cociuba%3C%2FA%3E%3CBR%20%2F%3Ereviewed%20by%3A%20Muna%20AlHasan%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3C%2FDIV%3E%3C%2FLINGO-BODY%3E
Microsoft

When debugging memory dumps from customers, I have come to see, quite often, a pattern that you should not use in your application if you don’t want to run into trouble. This pattern can be resumed in a simple rule: thou shall not create thy own threads in thy application! To show you what I mean, through a series of three blog articles I will create a simple application and show you what happens when we transgress this rule.

Let’s build a simple ISS (International Space Station) tracker application. I am basing my sample on a sample You can see a complete website that plots the position of the ISS on the map using the same API on this website: https://wheretheiss.at/. The sample code for the application we are about to write, can be downloaded from OneDrive here:


Background Threading Sample Applications

When you start the solution, you should see a page that allows to get telemetry data from the space station (which is catalogued as satellite 25544). Here is the page loaded in Internet Explorer and showing the same telemetry data:

clipboard_image_0.png

So how does this work? The page has a button called btnGetSatelliteInfoNow which, when clicked, will submit the page and run some code behind to fetch certain telemetry data for satellite 25544, which happens to be the International Space Station. The code behind has a click event associated to the button, which looks like this:

    protected void btnGetSatelliteInfoNow_Click(object sender, EventArgs e)
    {
        var satellite = FetchSatelliteInfo();
        lblTime.Text = UnixTimeStampToDateTime(satellite.timestamp).ToString();
        lblAltitude.Text = satellite.altitude.ToString();
        lblLatitude.Text = satellite.latitude.ToString();
        lblLongtitude.Text = satellite.longitude.ToString();
        lblVelocity.Text = satellite.velocity.ToString();
        pnlResults.Visible = true;
    } 

The code will call a method called FetchSatelliteInfo(), here is the code for this second method:

    private Satellite FetchSatelliteInfo()
    {
        string url = "https://api.wheretheiss.at/v1/satellites/25544";
        var request = (HttpWebRequest)WebRequest.Create(url);
        var reader = new StreamReader(request.GetResponse().GetResponseStream());
        string content = reader.ReadToEnd();
        reader.Close();
        var satellite = JsonConvert.DeserializeObject(content);
        return satellite;
    } 

The method will compose a request to the ISS API url – (notice the url contains the NORAD catalog id for the ISS, which is 25544), then sends the request to retrieve telemetry information as a JSON object. The JSON response containing the satellite information from ISS API should look something like this:

{
   "name":"iss",
   "id":25544,
   "latitude":42.2825687563,
   "longitude":18.004509864333,
   "altitude":424.54036183209,
   "velocity":27573.416280786,
   "visibility":"daylight",
   "footprint":4530.4910258379,
   "timestamp":1566134760,
   "daynum":2458714.0597222,
   "solar_lat":13.073971650332,
   "solar_lon":339.48156331088,
   "units":"kilometers"
} 

Then the code will attempt to read the response stream using System.IO.StreamReader reader, so it can be deserialized to a POCO ((short for Plain Old CRL Object) class that will represent the ISS’s telemetry at a given time.

Here is the code listing:

[JsonObject(MemberSerialization.OptIn)]
public class Satellite
{
    [JsonProperty]
    public string name { get; set; }

    [JsonProperty]
    public int id { get; set; }

    [JsonProperty]
    public double Latitude { get; set; }

    [JsonProperty]
    public double Longitude { get; set; }

    [JsonProperty]
    public double Altitude { get; set; }

    [JsonProperty]
    public double Velocity { get; set; }

    [JsonProperty]
    public string Visibility { get; set; }

    [JsonProperty]
    public double Footprint { get; set; }

    [JsonProperty ]
    public double Timestamp { get; set; }

    [JsonProperty]
    public double Daynum { get; set; }

    [JsonProperty]
    public double Solarlat { get; set; }

    [JsonProperty]
    public double Solarlon { get; set; }

    [JsonProperty]
    public string Units { get; set; }

}

This class only contains a couple of properties that expose both get and set so that we can store the data related to a satellite (in this case the ISS) inside an instance of the class and modify it later if we need to. This will represent our Business Layer (Model).


Following the execution of FetchSatelliteInfo, the rest of the event handler method for the button click will just display the values of the Satellite object instance which we have retrieve on the page.

To continue the development of the application, we will look at how to ‘optimize’ the code that I have proposed so far in this artilce. The objective would be to have the application load the data in the background via a thread that would update the telemetry data for the space station every X seconds.

To do this, what I have seen many of my customers do, is to spawn a new .Net thread in the background and have this thread run an infinite loop with the following pseudo-logic:

  1. When the application loads up, start the background thread and have it execute the infinite loop
  2. Once in the infinite loop, the thread will the telemetry data by making API calls
  3. When it has retrieved the information for the telemetry data, it will go to sleep for a few seconds.
  4. It will then resume the loop from the beginning and attempt to refresh the coordinates

So let’s look how this pseudo logic can be transformed into code. Keep in mind that I am doing the bare minimum to keep the application as simple as possible and focus on the essentials.

When the application loads into the process memory (into the w3wp.exe worker process), the Application_Start event is fired. This seems like a good place to add the code to create a background thread.


The first method I will implement is located in the Global.asax file (but I could have implemented this inside another class if I had wanted to as well). This method is called UpdateSatelliteInfo. Here is the code listing:

    private void UpdateSatelliteInfo()
    {
        string url = "https://api.wheretheiss.at/v1/satellites/25544";
        Satellite satellite; string content; HttpWebRequest request; StreamReader reader;
        do
        {

            request = (HttpWebRequest)WebRequest.Create(url);
            reader = new StreamReader(request.GetResponse().GetResponseStream());
            content = reader.ReadToEnd();
            reader.Close();
            satellite = JsonConvert.DeserializeObject(content);

            satellite.Time = UnixTimeStampToDateTime(satellite.Timestamp);
            Application["satellite"] = satellite;

            //sleep for 5 Seconds
            System.Threading.Thread.Sleep(5000);
        } while (true);
    }

What the method does is that it will update the Satellite Info (just to keep it simple – we could use something more dynamic afterwards) that will be refreshed every X seconds. Following this declaration, it will go into an infinite loop, represented by the do{} while(true) statement.


The Satellite telemetry data will be inspected, and we will try to obtain the current position for the ISS, by making a call to the ISS API using the StreamReader object. With every iteration of the while loop we compose the correct URL and then we ask the StreamReader object to retrieve the JSON datagram corresponding to the current state of the Satellite.


Once we have loaded the JSON content from the StreamReader inside the string object, the method will create a new instance of the Satellite class and populate its properties with data extracted from the JSON – via the JsonConvert.DeserializeObject<Satellite>(content) method, just like in the previous sample.


Note that we have to convert date time from the loaded JSON object, which is in unix format and which will be mapped by the JSON deserialization into a property of type Double, to an instance of type DateTime. To do so, I have created a method named UnixTimeStampToDateTime():

public static DateTime UnixTimeStampToDateTime(double unixTimeStamp)
    {
        // Unix timestamp is seconds past epoch
        System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);
        dtDateTime = dtDateTime.AddSeconds(unixTimeStamp).ToLocalTime();
        return dtDateTime;
    }

The newly created instance of the Satellite object will be added to the HttpApplication object, an object that is available in all parts of the application and that can be thought of as a global dictionary of variables. (Some of you might remark that I could have checked if I already had an entry for the Satellite inside the Application object and if so, I could just have performed an update on the object instead of creating a new instance every time, and you would be right to do so. However, in essence I am trying to keep the app basic, and not necessarily optimized).


Following the loading of the Satellite data, the loop will put the thread to sleep for 5 seconds. After this, the loop will iterate again and again, until the end of time, or the end of the process, whichever comes first.


Now for the interface to display Satellite data in a web-page. To do this, I have created a second page for the application, called AutoSatellite.aspx. This page contains a repeater control that is strongly–typed data-bound to an object of type Satellite, via the ItemType property. If you are new to strongly typed data-binding, I would suggest you have a look at my ASP.net 4.5 Webforms video tutorial:

http://linqto.me/n/ASPNet45


Here are the tags for the repeater control – note the ItemType tag that indicates the type of object that will be displayed by the control and the SelectMethod tag will indicate which method in the code behind is to be called to load the elements to display when the control is rendered:

clipboard_image_0.png

 

Inside the repeater control, we just display a fieldset tag for the Satellite Info, and inside this we display, the Time, the Alttitude and other information via strongly typed data-binding.


Inside the repeater control, we just display a fieldset tag for the Satellite Info, and inside this we display, the Time, the Alttitude and other information via strongly typed data-binding.

In the code behind, the GetSatellite() method does the loading of the satellite data from the Application object – here is the code:

     
 public Satellite GetSatellite()
    {
        //get the Satellite from the application object
        Satellite satellite = new Satellite();
        if (Application["satellite"] != null)
        {
            satellite = (Satellite)Application["satellite"];
        }
        return satellite;

    } 


The method declares a variable of type Satellite and attempts to assign the satellite info from the Application object to the newly created object. We check if satellite info in the Application object is not null. Should the background thread not have finished loading the satellite info for the first time before we show the page, we don’t want to show null data and crash the page, hence the reason for the test. It ensures that the data was loaded by the background thread at least once.

 

There is also a refresh button on the page, with a Click event handler in the code behind:

    protected void cmdRefresh_Click(object sender, EventArgs e)
    {
        //do nothing
        rptSatellite.DataBind();
    }

All this does is that it forces the repeater control to data-bind once again – and hence to call the GetSatellite() method and reload the data from the Application object. Note that the data will not be reloaded by the background thread when this new call to GetSatellite() comes in. It will be refreshed only when the background thread wakes up the next time around and loads new data from ISS.


You can find the sample completed with this new code in my OneDrive as well, by following this link:

https://onedrive.live.com/?id=9A83CB6EACC8118C%215695&cid=9A83CB6EACC8118C

In the next installment, I will discuss the problems with this kind of pattern and why it is not recommended you make use of it in your ASP.net applications.

 

written by: Paul Cociuba
reviewed by: Muna AlHasan