Created
July 22, 2011 05:59
-
-
Save ayende/1098963 to your computer and use it in GitHub Desktop.
Sample of what appears to be a memory leak in the WCF Discovery
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Diagnostics; | |
using System.Linq; | |
using System.Net.Security; | |
using System.ServiceModel; | |
using System.ServiceModel.Discovery; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace ConsoleApplication7 | |
{ | |
internal class Program | |
{ | |
private static int NextPort = 12323; | |
private static void Main(string[] args) | |
{ | |
var doNotGc = new List<ServiceHost>(); | |
for (int i = 0; i < 15; i++) | |
{ | |
doNotGc.Add(OpenServiceHost()); | |
} | |
PrintMemory("Start: "); | |
for (int i = 0; i < 15; i++) | |
{ | |
var discoveryClient = new DiscoveryClient(new UdpDiscoveryEndpoint()); | |
var findCriteria = new FindCriteria(typeof(IDiscoverableService)) | |
{ | |
Duration = TimeSpan.FromSeconds(1) | |
}; | |
discoveryClient.Find(findCriteria); | |
discoveryClient.Close(); | |
PrintMemory(i.ToString()); | |
} | |
PrintMemory("Done: "); | |
foreach (var serviceHost in doNotGc) | |
{ | |
serviceHost.Close(); | |
} | |
PrintMemory("Cleanup: "); | |
} | |
private static void PrintMemory(string title) | |
{ | |
GC.Collect(GC.MaxGeneration); | |
Console.WriteLine("{1} WorkingSet: {0:#,#} kb", Process.GetCurrentProcess().WorkingSet64 / 1024, title); | |
} | |
private static ServiceHost OpenServiceHost() | |
{ | |
var serviceHost = new ServiceHost(new DiscoverableService()); | |
serviceHost.Description.Behaviors.Add(new ServiceDiscoveryBehavior()); | |
serviceHost.AddServiceEndpoint(new UdpDiscoveryEndpoint()); | |
var myAddress = new UriBuilder("net.tcp", Environment.MachineName, NextPort++, "/Discoverable").Uri; | |
serviceHost.AddServiceEndpoint(typeof (IDiscoverableService), new NetTcpBinding(SecurityMode.None), | |
myAddress); | |
serviceHost.Open(); | |
return serviceHost; | |
} | |
} | |
[ServiceContract(ProtectionLevel = ProtectionLevel.None)] | |
public interface IDiscoverableService | |
{ | |
[OperationContract] | |
void DoSomething(); | |
} | |
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)] | |
public class DiscoverableService : IDiscoverableService | |
{ | |
public void DoSomething() | |
{ | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment