Bug 1839 - Leak in HttpWebRequest
Summary: Leak in HttpWebRequest
Status: RESOLVED DUPLICATE of bug 1999
Alias: None
Product: iOS
Classification: Xamarin
Component: XI runtime ()
Version: 5.0
Hardware: Macintosh Mac OS
: --- normal
Target Milestone: Untriaged
Assignee: Bugzilla
URL:
Depends on:
Blocks:
 
Reported: 2011-11-02 14:51 UTC by Mark Strawmyer
Modified: 2011-12-01 07:45 UTC (History)
2 users (show)

Tags:
Is this bug a regression?: ---
Last known good build:

Notice (2018-05-24): bugzilla.xamarin.com is now in read-only mode.

Please join us on Visual Studio Developer Community and in the Xamarin and Mono organizations on GitHub to continue tracking issues. Bugzilla will remain available for reference in read-only mode. We will continue to work on open Bugzilla bugs, copy them to the new locations as needed for follow-up, and add the new items under Related Links.

Our sincere thanks to everyone who has contributed on this bug tracker over the years. Thanks also for your understanding as we make these adjustments and improvements for the future.


Please create a new report on Developer Community or GitHub with your current version information, steps to reproduce, and relevant error messages or log files if you are hitting an issue that looks similar to this resolved bug and you do not yet see a matching new report.

Related Links:
Status:
RESOLVED DUPLICATE of bug 1999

Description Mark Strawmyer 2011-11-02 14:51:19 UTC
I have an application where I am making a number of calls to REST based services.  I build small objects, serialize them, submit, and then read and deserialize a response.

After a number of calls to the GetResponse() method of a HttpWebRequest, I start to see messages like:

2011-11-02 14:43:55.133 SIMSMobile[36826:4003] *** __NSAutoreleaseNoPool(): Object 0x75aecf0 of class __NSArrayI autoreleased with no pool in place - just leaking
2011-11-02 14:43:55.134 SIMSMobile[36826:4003] *** __NSAutoreleaseNoPool(): Object 0x76a8f90 of class __NSArrayM autoreleased with no pool in place - just leaking

I used Console.Writeline to put debug statements in my code and narrowed it down to when I do 

WebResponse response = invokeRequest.GetResponse();

where invokeRequest is an HttpWebRequest instance.

I had previously emailed this to the support email as well before I found the Bugzilla site for logging items.

Here is the code in question that does the call:

protected T IntegrationCall<T,I>(string methodName, I input)
		{
			var invokeRequest = WebRequest.Create(GetMethodURL(methodName)) as HttpWebRequest;

			invokeRequest.Credentials = new NetworkCredential(CommonData.CredentialsUserName, CommonData.CredentialsPassword, CommonData.CredentialsDomain);
			invokeRequest.Method = "POST";
			invokeRequest.ContentType = "text/xml";
			invokeRequest.Timeout = 40000;
			
			using( Stream requestObjectStream = new MemoryStream() )
			{
				DataContractSerializer serializedObject = new DataContractSerializer(typeof(I));
				serializedObject.WriteObject(requestObjectStream, input);
				requestObjectStream.Position = 0;
				
				invokeRequest.ContentLength = requestObjectStream.Length;
				using (Stream postStream = invokeRequest.GetRequestStream())
           			requestObjectStream.CopyTo (postStream);
			}
			
			WebResponse response = invokeRequest.GetResponse();
			T result = default(T);
			
            // Get the stream containing content returned by the server.
            using(Stream dataStream = response.GetResponseStream())
			{
				XmlDictionaryReaderQuotas quotas = new XmlDictionaryReaderQuotas();
				quotas.MaxArrayLength = 80000000;
				quotas.MaxStringContentLength = 80000000;
				
				using( XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(dataStream, quotas) )
				{					
					DataContractSerializer deserializedObject = new DataContractSerializer(typeof(T));
					
					// Deserialize the data and read it from the instance.
					result = (T) deserializedObject.ReadObject(reader, true);
				}
			}
			
			invokeRequest.Credentials = null;
			invokeRequest = null;
			response = null;
			return result;
		}
Comment 1 Rolf Bjarne Kvinge [MSFT] 2011-11-03 05:32:53 UTC
Are you creating your own threads or are you using the threadpool? If you're creating your own threads, then can you show the code where you're creating the AutoreleasePools?
Comment 2 Mark Strawmyer 2011-11-03 07:43:51 UTC
We are regularly creating threadpools to execute things on a background thread.

Here is an example of the common code structure for our REST Calls:
		private void GetAppraisalLogData()
		{
			loadmore.Animating = true;
			UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true;
			
			// Start running on the backgrond thread
			Utilities.Common.ExecuteOnBackgroundThread(delegate {
				try
				{
					AppraisalLogParams p = new AppraisalLogParams();
					p.StoreID = CommonData.SelectedStore.StoreId;
					p.StatusList = "101,102,103";
					p.DateType = "Last 30 days";
					p.StartRow = StartingRecord;
					p.EndRow = EndingRecord;
					p.SortByField = "CreatedDate";
					p.SortDirection = "DESC";
					
					Sonic.SIMS.Mobile.Enhancement.Integrations.AppraisalLog al = new Sonic.SIMS.Mobile.Enhancement.Integrations.AppraisalLog();
					AppraisalLogEntityResponse resp = al.GetAppraisalLog(p);
					
					// Now that we are done, go back to the previous thread
					Utilities.Common.ExecuteOnMainThread(delegate {	
						UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
						try
						{					
							// put into the records into the dialog to be displayed
							if (resp.AppraisalLogEntityList != null)
							{
								foreach (var r in resp.AppraisalLogEntityList)
								{							
									mainSection.Insert(mainSection.Count > 0 ? mainSection.Count-1 : 0,
								                   new InventoryElement(ref CellControllers, r.Vehicle_ID, r.Invtr_ID, r.Year.HasValue ? r.Year.Value : (short)0, 
									                                        r.Make, r.Model, r.ExteriorColor, r.SalesPerson, r.Status, 
									                                        r.WizardPage != null && r.WizardPage.HasValue ? r.WizardPage.Value : (byte)1, 
									                                        RecordTapped) );
								}
							}
							
							loadmore.Animating = false;
							if (resp == null || resp.AppraisalLogEntityList == null || resp.AppraisalLogEntityList.Count < Utilities.Common.PageSize)
							{
								mainSection.Remove(loadmore);
							}
							
							if( resp != null && resp.AppraisalLogEntityList != null )
							{
								resp.AppraisalLogEntityList.Clear();
								resp = null;
							}
						}
						catch
						{
							mainSection.Remove(loadmore);
							Utilities.Common.DisplayMessage("Error Displaying", "An error occurred while updating the display.  Please try again.");
						}
					});
				}
				catch
				{
					Utilities.Common.ExecuteOnMainThread(delegate {
						UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
						mainSection.Remove(loadmore);
						Utilities.Common.DisplayMessage("Error Loading", "An error occurred while retrieving the data.  Please verify your connectivity and try again.");
					});
				}
			});
		}

Here are the helper methods used for switching threads:
public static void ExecuteOnMainThread(NSAction action)
		{
			UINavigationController nav = null;
		
			if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad)
			{
				nav = GetiPadAppDelegate().MainNavigationController;
			}
			else
			{
				nav = GetiPhoneDelegate().MainNavigationController;
			}
			
			nav.InvokeOnMainThread(action);
		}

public static void ExecuteOnBackgroundThread(WaitCallback callback)
		{
			Thread t = new Thread(delegate() 
          	{ 
				using(var pool = new NSAutoreleasePool())
				{
					callback.Invoke(null);
				}
			});
			
			t.Start();
		}
Comment 3 Mark Strawmyer 2011-11-08 08:53:57 UTC
Does anything look off with the way that I create my threadpool?
Comment 5 Rolf Bjarne Kvinge [MSFT] 2011-12-01 07:45:03 UTC
This looks like the same issue as in #1999 (which was recently fixed).

*** This bug has been marked as a duplicate of bug 1999 ***