Skip to main content

C# 5.0: Asynchronous Operations

 Asynchronous functions: is a new feature in C# which provides an easy means for expressing asynchronous operations. Inside asynchronous functions await expressions can await ongoing tasks, which causes the rest of the execution of the asynchronous function to be transparently signed up as a continuation of the awaited task. In other words, it becomes the job of the programming language, not the programmer, to express and sign up continuations. As a result, asynchronous code can retain its logical structure.

An asynchronous function is a method or anonymous function which is marked with the async modifier. A function without the async modifier is called synchronous. An asynchronous function in C# must either return void or one of the types Task or Task.

Await expressions: Await expressions are used to suspend the execution of an asynchronous function until the awaited task completes. An await expression is only allowed when occurring in the body of an asynchronous function. Inside of the innermost enclosing asynchronous function it may furthermore not occur inside of the body of a synchronous function, in a catch or finally block of a try-statement, inside the block of a lock-statement, or in an unsafe context.

Since an await expression can only occur in an asynchronous function, it can never be confused with uses of await as an identifier already occurring in code written in older versions of C#.

Example: 
Task<Movie> GetMovieAsync(string title);
Task PlayMovieAsync(Movie movie);
async void GetAndPlayMoviesAsync(string[] titles)
{
    foreach (var title in titles)
    {
        var movie = await GetMovieAsync(title);
        await PlayMovieAsync(movie);
    }
}

By convention asynchronous operations use the postfix “Async” to show that part of their execution may take place after the method call has returned. Both GetMovieAsync and PlayMovieAsync return tasks, which means that their completion can be subsequently await’ed. By contrast, GetAndPlayMoviesAsync returns void, so its completion cannot be await’ed. Such asynchronous operations are often referred to as “fire and forget”, and are useful e.g. for implementing event handlers asynchronously.

GetAndPlayMoviesAsync is marked by the async modifier as an asynchronous function, containing two await expressions. This fact is an implementation detail to its callers, but fundamentally changes the way the method is executed: As soon as an unfinished Task is awaited, it will return to its caller. When the awaited Task completes, it will resume execution of the GetAndPlayMoviesAsync method until the next unfinished Task is awaited, and so on. In between, while awaiting unfinished Tasks, no thread is occupied with the execution of this method: it “borrows time” on threads only when it is active.

Popular posts from this blog

WCF Service Exception PlainXmlWriter+MaxSizeExceededException

For a WCF service the exception 'System.ServiceModel.Diagnostics.PlainXmlWriter+MaxSizeExceededException' generally occurs when we switched on logging and tracing.   A message was not logged. Exception: System.InvalidOperationException: There was an error generating the XML document. ---> System.ServiceModel.Diagnostics.PlainXmlWriter+MaxSizeExceededException: Exception of type 'System.ServiceModel.Diagnostics.PlainXmlWriter+MaxSizeExceededException' was thrown.   The reason is that "maxSizeOfMessageToLog" configuration parameter value is set to a value lower than the size of the message to log. < system.serviceModel>   < diagnostics > <!-- log all messages received or sent at the transport or service model levels --> < messageLogging logEntireMessage = " true " logMessagesAtServiceLevel = " true " logMalformedMessages = " true " logMessagesAtTransportLevel = " true "    maxMessa...

ISAPI & CGI Restriction configuration missing in IIS

In windows 7 by default ISAPI & CGI Restrictions are not configured. To enable ISAPI & CGI restrictions, GoTo -> Control Panel -> Programs -> Click on "Windows features on or off -> Expand Internet Information Services - >Expand World Wide Web Services ->Select CGI and ISAPI extensions and Click OK. After enabling, Check in IIS, Open your IIS and the feature will be available. What is ISAPI and CGI restrictions : ISAPI and CGI restrictions are request handlers that allow dynamic content to execute on a server. These restrictions are either CGI files (.exe) or ISAPI extensions (.dll). You can add custom ISAPI or CGI restrictions if the IIS configuration system allows this.

Implementing Parallelism With A SearchResultCollection

Implementing Parallel.ForEach with a SearchResultCollection: The below piece of code helps to check the given user is a part of the given active directory group. To implement Parallel.ForEach with a SearchResultCollection, do the casting with the SearchResult object and covert it into a list. //// Directory Searcher var directorySearcher = new DirectorySearcher(string.Format("(CN={0})", groupName)); //// Find group var searchResultCollection = directorySearcher.FindAll().Cast ().ToList(); Parallel.ForEach(searchResultCollection, searchResult => {  // enumerate members  var resultPropColl = searchResult.Properties;  Parallel.ForEach(resultPropColl["member"].Cast ().ToList(), member =>  {    var memberEntry = new DirectoryEntry("LDAP://" + member);    var userProperties = memberEntry.Properties;    if (GetUserNameFromProperties(userProperties, "sAMAccountName") == userName)    {      return true; ...