C#: Asynchronical Function Calls

As a Web Developer, I’ve frequently have had the need to make asynchronical function calls.

Usually, you need to do async calls when:

  • Function takes a long time to process
  • There is no need to present a response to the user

In this example, I will be showing some code I use on my Facebook Application (Network Trotters) to update the users profiles.

As a quick contextual background, user profiles are cached on Facebook’s side, and periodically I need to clear the cache so it is updated. This action can take a bit of time when you have a high number of users, but it doesn’t really require any response to the user.

There are 3 main things you need to do to create an async call:

  1. Create a delegate with the signature you would like
  2. Implement a Function with the same function as the delegate
  3. Call the delegate


Create a delegate

public delegate void AsyncDelegate(FacebookService fbService, string connectionString);

With the code above, I hve created an async delegate that takes 2 parameters, an FacebookService class (see references below), and a connection string.

Implement a Function

The next step if to implement the function we want to call, as shown in the code below:

public void RefreshProfiles(FacebookService fbService, string connectionString)
{
try
{

//get users ids
foreach (string userId in userIds)
{
//refresh the profile url
fbService.RefreshRefUrl(string.Format("{0}?uid={1}", Resources.FbAppSettings.ProfileHandlerUrl, userId));
}
}
catch
{
//ex management.
}
}

This particular call is refreshing a previously set URL from Facebook’s cache. This is how I manage to refresh profiles. I call this function periodically. I keep a cache with the last time I ran it, and that way I control how often I want it to run.

Check out my previous post for more info on Facebook Profile Management.

Call Function

// Create the delegate.
AsyncDelegate refreshProfileDelegate = new AsyncDelegate(profileRefresher.RefreshProfiles);

// Initiate the asychronous call.
IAsyncResult ar = refreshProfileDelegate.BeginInvoke(fbService, connectionString, null, null);

First step is to create a delegate,and as an input you put the previously created function.

Second step is to invoke the delegate you just created. In this example I do not receive anything back from the function, so I send callback and object as null.

References

To get more information about check out:

Complete Code

//Deleage definition
public delegate void AsyncDelegate(FacebookService fbService, string connectionString);

public class ProfileRefresher
{
public ProfileRefresher()
{
}

public static void Run(FacebookService fbService, string connectionString)
{
//if is null we need to update
if (HttpContext.Current.Cache["UpdateProfiles"] == null)
{
ProfileRefresher profileRefresher = new ProfileRefresher();

// Create the delegate.
AsyncDelegate refreshProfileDelegate = new AsyncDelegate(profileRefresher.RefreshProfiles);

// Initiate the asychronous call.
IAsyncResult ar = refreshProfileDelegate.BeginInvoke(fbService, connectionString, null, null);

//we set the cache
HttpContext.Current.Cache.Add("UpdateProfiles", true, null,
DateTime.Now.AddMinutes(60),
Cache.NoSlidingExpiration, CacheItemPriority.High, null);
}
}

public void RefreshProfiles(FacebookService fbService, string connectionString)
{
try
{
//Get user Ids -
foreach (string userId in userIds)
{
fbService.RefreshRefUrl(string.Format("{0}?uid={1}", URL_STATIC, userId));
}
}
catch
{
//ex management.
}
}
}

Author: ricardocovo

Senior Software Architect/Developer with extensive experience in web related technologies.

Leave a comment