In Silverlight, all the WCF service calls are asynchronous. After the call to the WCF service is completed, a Completed event is called at the Silverlight UI side.Sometimes it becomes necessary to determine which task raised the Completed event.In this case you can use the "UserState" property to determine this.
For Example:
You want to download files from the server, and when the download is complete you want to show the filename that was downloaded. In the sample below "DownloadFileAsync" is the WCF function that is called asynchronously, "webServiceClient_DownloadFileCompleted" is the completed event for the WCF service call, "Filename" has the filename that is downloading.
Silverlight code-behind code:
private void DownloadSingleFile()
{
// Set user state here
{
// Set user state here
webServiceClient.DownloadFileAsync(new Uri(downloadUrl), Filename);
}
}
void webServiceClient_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
txtStatus.Text = "File : " + e.UserState + " downloaded uccessfully !";
}
WCF Service code:
public byte[] DownloadFile(string uri)
{
// logic to read the file and send back
}
As you might have noticed, the method "DownloadFile" takes only one parameter as input i.e. URI of the file to be downloaded but while calling the method we are passing two parameters, the second parameter is the "UserState" object
Note: The "UserState" property is of "Object" type so you can pass variable of any datatype.
Hope this helps. Happy Coding !
2 comments:
In async programming model it becomes very necessary to know which part is completed amongst all. Good article !
@HITESH AGJA Thanks :)
Post a Comment