Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Finally code
Message
Information générale
Forum:
ASP.NET
Catégorie:
Autre
Titre:
Divers
Thread ID:
00970841
Message ID:
00970976
Vues:
13
This is a little piece of code that explains it a bit more:
using System;

namespace ConsoleApplication1
{
	class Class1
	{
		private static bool error = true;
		[STAThread]
		static void Main(string[] args)
		{
			try
			{
				using ( TestDispose test = new TestDispose() )
				{
					// Some code
					Console.WriteLine("using the test object");
					if (error)
						throw new Exception("This is an exception");
					Console.WriteLine("Continue using the test object");
			
				}
			}
			catch (Exception e)
			{
				Console.WriteLine(e.Message);
			}
		}
	}
	
	public class TestDispose : IDisposable
	{
		#region IDisposable Members

		public void Dispose()
		{
			Console.WriteLine("Dispose");
			this.Close();
		}
		private void Close()
		{
			Console.WriteLine("Closing resources" );
		}

		#endregion
	}
}
>The Socket class does implement IDisposable so I should be able to use the using () {}.
>One thing I don't understand about using using is what happends if an error is thrown outside of the using statement?
>
>Example:
>
>using (ResourceType resource = expression)
>{
>  //code that throws an error that is not handled inside the using statement
>}
>
>Would it still clean up stuff for me even if the error throws it outside the using statement?
>
>Einar
>
>
>>What you could do if the Socket class suports IDisposable is use a using statement, that way, you don't have to worry about writing a finnally block, the Scocket object will dispose itself.
>>
>>
>>using (Socket udpSocket = new Socket(ipEP.Address.AddressFamily,SocketType.Dgram,ProtocolType.Udp))
>>{
>>	// some more code				
>>}
>>
>>
>>
>>HTH
>>>I can not remember the exact syntax for what I want to do, but I am sure this is used all over the place.
>>>Considder the code:
>>>
>>>try
>>>{
>>>  // some code
>>>  IPEndPoint ipEP = new IPEndPoint(paraIPAddress, iPort);
>>>  Socket udpSocket = new Socket(ipEP.Address.AddressFamily,SocketType.Dgram,ProtocolType.Udp);
>>>  // some more code
>>>}
>>>catch(Exception ex)
>>>{
>>>  //Do something if exception is thrown
>>>}
>>>finally
>>>{
>>>  //I need some code here to test if the socket is created/initialized
>>>  udpSocket.Close();
>>>}
>>>
>>>
>>>The contents of the code is not really important, but what can I use in the finally block to ensure that the object that I am trying to call the "clean-up" code for (in this case Close()) has been initialized? What if an error was thrown before the line Socket udpSocket = new Socket(...), I want to call Close() on the udpSocket in the finally block but only if the object udpSocket is defined.
>>>
>>>Thanks,
>>>Einar
Précédent
Suivant
Répondre
Fil
Voir

Click here to load this message in the networking platform