Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Comparison of C Sharp and Java
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
=== Task-based parallelism for C# === With .NET Framework 4.0, a new task-based programming model was introduced to replace the existing event-based asynchronous model. The API is based around the {{mono|Task}} and {{code|Task<T>}} classes. Tasks can be composed and chained. By convention, every method that returns a {{mono|Task}} should have its name postfixed with ''Async''. <syntaxhighlight lang="csharp"> public static class SomeAsyncCode { public static Task<XDocument> GetContentAsync() { HttpClient httpClient = new HttpClient(); return httpClient.GetStringAsync("www.contoso.com").ContinueWith((task) => { string responseBodyAsText = task.Result; return XDocument.Parse(responseBodyAsText); }); } } var t = SomeAsyncCode.GetContentAsync().ContinueWith((task) => { var xmlDocument = task.Result; }); t.Start(); </syntaxhighlight> In C# 5 a set of language and compiler extensions was introduced to make it easier to work with the task model. These language extensions included the notion of {{mono|async}} methods and the {{mono|await}} statement that make the program flow appear synchronous. <syntaxhighlight lang="csharp"> public static class SomeAsyncCode { public static async Task<XDocument> GetContentAsync() { HttpClient httpClient = new HttpClient(); string responseBodyAsText = await httpClient.GetStringAsync("www.contoso.com"); return XDocument.Parse(responseBodyAsText); } } var xmlDocument = await SomeAsyncCode.GetContentAsync(); // The Task will be started on call with await. </syntaxhighlight> From this [[syntactic sugar]] the C# compiler generates a state-machine that handles the necessary continuations without developers having to think about it.
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)