In Part 4 of the Peer to Peer Series, I modify the Resolve program to find Peer Names using the asynchronous methods. Below is a very simple example of using the ResolveAsync method:
PeerNameResolver resolver = new PeerNameResolver();
try
{
resolver.ResolveCompleted += new EventHandler<ResolveCompletedEventArgs>(resolver_ResolveCompleted);
resolver.ResolveAsync(new PeerName(classifier, PeerNameType.Secured), Guid.NewGuid());
}
catch (PeerToPeerException ex)
{
// There are other standard exceptions you can also catch - see docs
Console.WriteLine("PeerToPeer Excpetion: {0)", ex.Message);
}
static void resolver_ResolveCompleted(object sender, ResolveCompletedEventArgs e)
{
if (!e.Cancelled && e.Error == null && e.PeerNameRecordCollection != null)
{
records = e.PeerNameRecordCollection;
DisplayResults();
}
}
There is also a ResolveProgress event you can also wire up. As the name implies, it will fire periodically to indicate the progress being made in resolving the Peer Name. It was not overly useful when resolving a Peer Name that had a small number of results, but your mileage may vary.
The one thing that is also a “brute force” implementation in the demo code is how I pass a Guid.NewGuid() into the ResolveAsync method. The Guid is being used as the UserState parameter in the method, and can actually be any Object. In a real implementation where you may have multiple ResovleAsync requests in-flight at any one time, you would want to implement a tracking system using this UserState parameter so you could match up the corresponding ResolveCompleted event with the correct initiating request. The ResolveCompleteEventArgs parameter contains the UserState used to initiate the request, so the matching is pretty straightforward. I did not go the extra mile and implement that since the demo only fired a single ResolveAsync request. You cannot pass in a null UserState object, so I went with a simple Guid for no particularly good reason.
Other documentation for PNRP:
View the Screencast:
Download the Demo Code