--> Serializing Delegates - Impersonation Failure

Serializing Delegates

Saw this interesting article from March 2003 by Richard Grimes on Windows Developer Network on Serializing Delegates. Interesting concept, you can serialize your delegate today, store it somewhere and later deserialize it on another machine and invoke it. All targets held in the delegate should be serializable as they all need to be serialized with the delegate so when you deserialize the original context is regenerated. Read the article it's pretty interesting, although as he mentions, I'm not sure what practical use you'll have for this.

I've converted the code to C#, so here's a quick sample that illustrates the point, it's a console application that serializes a delegate and on next run you can deserialize the stored delegate and invoke it.

using System;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Soap;
using System.IO;

namespace SerializingDelegates
{
	[Serializable]
	public class Jane
	{
		public void SayHello()
		{
			Console.WriteLine("Hi, I'm Jane");
		}
	}

	[Serializable]
	public class John
	{
		public void SayHello()
		{
			Console.WriteLine("Hi, I'm John");
		}
	}

	public delegate void Del();

	class Class1
	{
		[STAThread]
		static void Main(string[] args)
		{
			string a = string.Empty;
			Console.Write("Deserialize / Serialize (d/s) : ");a = Console.ReadLine();
			switch(a)
			{
				case "s":	CallAndSave();	break;
				case "d":	LoadAndCall();	break;
			}	
			Console.ReadLine();
		}

		private static void CallAndSave()
		{
			Del d = new Del(new John().SayHello);			
			d += new Del(new Jane().SayHello);
			d();
		
			FileStream fs = new FileStream(@"c:\temp\serializeddelegates.xml",FileMode.Create);
			SoapFormatter sf = new SoapFormatter();
			sf.Serialize(fs,d);
			fs.Close();			
		}

		private static void LoadAndCall()
		{	
			FileStream fs = new FileStream(@"c:\temp\serializeddelegates.xml",FileMode.Open);
			SoapFormatter sf = new SoapFormatter();
			Del d = (Del)sf.Deserialize(fs);
			fs.Close();
			d();
		}
	}
}
Filed under:

Comments

# Corne said:

Very cool.... I never thought you could serialize a delegate in this way.....

Friday, April 02, 2004 8:48 AM
# Mark Mullin's Professional Blog said:

In this posting I am going to lay some of the groundwork for explaining what continuations are, why they...

Wednesday, April 25, 2007 2:47 PM