21. October 2009 16:44
by Chakkaradeep
1 Comments
In the SharePoint 2010: Getting Started With Client Object Model blog post, we built a simple SharePoint console application using Client OM. We queried synchronously which is good for simple operations, but you would like to query asynchronously too if you intend to have more queries to the SharePoint server. Below are simple yet easy steps to query asynchronously.
Step 1 – Create a new class for our Asynchronous operations
Create a new class ClientOMAsync
Step 2 – Create a delegate for our Query
public class ClientOMAsync
{
delegate void ExecuteAyncQuery();
}
Add the required variables you want to use
Step 3 – Declare our variables
public class ClientOMAsync
{
delegate void ExecuteAyncQuery();
Web site;
ClientContext context;
}
Step 4 – Create the Run method
public void Run()
{
context =
new ClientContext(http://<your-site>);
site = context.Web;
context.Load(site, s => s.Title);
ExecuteAyncQuery executeQueryAsync = new ExecuteAyncQuery(context.ExecuteQuery);
executeQueryAsync.BeginInvoke(callback, null);
}
Pretty basic Asynchronous programming model and notice again that we are fetching only the Title property.
Step 5 – Create our Callback method
void callback(IAsyncResult arg)
{
Console.WriteLine("Aync Callback!");
Console.WriteLine("Title before changing: {0}",site.Title);
site.Title = site.Title + " Async";
site.Update();
context.ExecuteQuery();
Console.WriteLine("Title after the change: {0}",site.Title);
Console.WriteLine("Query completed!");
}
Step 6 – Perform the Asynchronous Client OM
Below is the code block that starts this asynchronous query operation from the Main method in the console application
static void Main(string[] args)
{
ClientOMAsync clientOMAsync = new ClientOMAsync();
clientOMAsync.Run();
Console.WriteLine("This is end of the Main program");
Console.Read();
}
And here is our Output:
Below is the full code for ClientOMAsync class:
public class ClientOMAsync
{
delegate void ExecuteAyncQuery();
Web site;
ClientContext context;
public void Run()
{
context =
new ClientContext("http://demo2010a");
site = context.Web;
context.Load(site, osite => osite.Title);
ExecuteAyncQuery executeQueryAsync = new ExecuteAyncQuery(context.ExecuteQuery);
executeQueryAsync.BeginInvoke(callback, null);
}
void callback(IAsyncResult arg)
{
Console.WriteLine("Aync Callback!");
Console.WriteLine("Title before changing: {0}",site.Title);
site.Title = site.Title + " Async";
site.Update();
context.ExecuteQuery();
Console.WriteLine("Title after the change: {0}",site.Title);
Console.WriteLine("Query completed!");
}
}