How can I retrieve a Gamer Profile asynchronously?

From XNAWiki
Jump to: navigation, search


This code shows how to asynchronously retrieve gamer profiles and use them in a useful manner.

//First add these two methods inside of your class you intend to use this code in.
 
void endGetProfile(IAsyncResult result)   
 {   
    int currentGamer = (int)result.AsyncState;   
    int nextGamer = currentGamer + 1;   
 
    profiles[currentGamer] = networkSession.AllGamers[currentGamer].EndGetProfile(result);   
 
    if (nextGamer < networkSession.AllGamers.Count)   
    networkSession.AllGamers[nextGamer].BeginGetProfile(endGetProfile, nextGamer);   
 }   
 
void getProfiles()   
 {   
   profiles = new GamerProfile[networkSession.AllGamers.Count];   
   networkSession.AllGamers[0].BeginGetProfile(endGetProfile, 0);   
 }  
 
//Now inside of your LoadContent() method create a GamerJoined Event Handler.
 
public override void LoadContent()
{
    networkSession.GamerJoined += new EventHandler<GamerJoinedEventArgs>(networkSession_GamerJoined); 
 
    //Rest of your content loading.
}
 
//Add this Event Handler that is called from the LoadContent() method.
void networkSession_GamerJoined(object sender, GamerJoinedEventArgs e)   
{   
   getProfiles();   
}  
 
//At this point you can now access all of the gamer profile information using a for loop. 
//What you access is up to you, but here is some example code to help you out. 
//The following code pulls out the gamer picture from a gamer profile and then displays that gamer picture on-screen.
 
public override Draw(GameTime gameTime)
{
   spriteBatch.Begin();
 
   spriteBatch.Draw(screenBG, Vector2.Zero, Color.White);
 
   // Draw all the gamers in the session and their respective gamer pic.
   int gamerCount = 0;
 
   if (profiles != null)
     {
 
         for (int a = 0; a < networkSession.AllGamers.Count; a++)
          {
             Vector2 picPosition = Vector2.Zero;
             Vector2 offset = new Vector2(1, 1);
             if (a < 8)
             {
                picPosition = new Vector2(88, 60 + (a * font.LineSpacing));
             }
 
             if (a > 7)
             {
                picPosition = new Vector2(461, 60 + ((a - 8) * font.LineSpacing));
             }
 
             if (profiles[a] != null)
             {
               Texture2D gamerPic = profiles[a].GamerPicture;
               spriteBatch.Draw(gamerPicBG, picPosition - offset, null, Color.White, 0f, new Vector2(0,0), 0.40f, SpriteEffects.None, 0);
               spriteBatch.Draw(gamerPic, picPosition, null, Color.White, 0f, new Vector2(0,0), 0.40f, SpriteEffects.None, 0);
             }
          }
   spriteBatch.End();
}