Peer to Peer Series Part 4: Resolving Peer Names Asynchronously

9/16/2009 9:08:00 AM

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

Tags:

Peer2Peer

Powered by BlogEngine.NET 1.6.0.0
Theme by Mads Kristensen

About the author

Jeff Brand Jeff Brand

This is the personal web site of Jeff Brand, self-proclaimed .NET Sex Symbol and All-Around Good guy. Content from my presentations, blog, and links to other useful .NET information can all be found here.

E-mail me Send mail


Calendar

<<  February 2012  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
2728291234
567891011

View posts in large calendar

My Twitter Updates

XBOX
Live

Recent comments

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2012

Sign in