C++ std::async vs async/await in C# - c#

I'm wondering if the new c++ feature std::async is quite comparable to the two C# keywords async/await or not and if not why?

Not really, assuming I'm reading this std::async documentation correctly.
C# 5's async/await feature involves a complex compiler transformation of the asynchronous method so that you can write code which looks pretty much synchronous, but has points of asynchrony. The compiler builds a state machine for you, creates appropriate callbacks etc.
EDIT: While I previously believed that std::async simply forced you to pass in a callback explicitly, it looks like it's even more primitive than that. Either way, I believe it's mostly/completely a library feature whereas C# 5's asynchronous methods are mostly a language feature with library support.
EDIT: As noted further in comments, it looks like it's on its way for VC++...

CPPASYNC (provided in another answer) looks like what you are looking for. The "Async" part is easy and the performance looks good (likely better than the C# implementation).
It's ugly b/c you need special "Await" wrappers around async callback calls. Some Boost networking is provided, and they're easy to make, but you can't just "Await" anything:
Async any method/function,
Within an Async function, await either:
- An Async function
- An await wrapper (simple to make) around an asynchronous function (that takes a callback)

Related

Is asynchronous in C# the same implementation as in F#?

Is the asynchronous implementation in C# 4.5 exactly the same as in F# 2 in the way threads are used?
They are different. The main difference is that C# uses standard .NET Task<T> to represent asynchronous computations while F# uses its own type called Async<T>.
More specifically, the key differences are:
A C# async method creates a Task<T> that is immediately started (hot task model) while F# creates a computation that you have to start explicitly (generator model). This means that F# computations are easier to compose (you can write higher level abstractions).
In F# you also get better control over how is the computation started. You can start a computation using Async.Start to start it in the background or Async.StartImmediate to start it on the current thread.
F# asynchronous workflows support cancellation automatically, so you do not have to pass CancellationToken around.
Perhaps another consequence of the first point is that F# async workflows also support tail-recursion, so you can write recursive workflows (this would not work easily in C#, but C# does not use this programming style)
I wrote a more detailed article about this topic: Asynchronous C# and F# (II.): How do they differ?

Async calls chaining in Metro app

I am quite new to Metro dev and I only hope I will be able to express my question in an understandable way...
Actually I am porting a part of my old application to Metro. The logic part is a separated project (Portable Library) and it should serve to 1) the old WPF app and 2) the new Metro app. The basic logic is the same but some subsystems (for example file operations manager) must be coded differently - i.e. async way for Metro.
My question is: Do I have to rewrite the whole chain of methods caller-callee to the new async paradigm? Let's say I have a chain of 4 methods, starting by method A = Metro UI event async handler (it makes sense to me to code it as async void as it is the top fire&forget event), through the next 2 methods (B and C) placed in different layers of my application, down to the method D containing "await CreateFileAsync" method (made async by Microsoft).
Now: async CreateFileAsync method should be called with await. That forces me to make method D async too. To call method D from C and C from B and B from A - do I have to rewrite all A, B and C into the async-await style?
I can feel I am missing a deeper knowledge so I am trying to educate myself but concurrently I wanted to try my luck here...
Do I have to rewrite a big part of my code? Is any of my statements above wrong?
Many thanks in advance, Hans
I recommend that you do rewrite your portable library to be asynchronous. It's not as bad as it used to be; Microsoft worked very hard on async/await to make it as easy as possible to convert synchronous code to asynchronous. I expect that a whole lot of others will be doing the same in the near future, and R# will probably implement a "make async" rewriting.
There are non-obvious pitfalls when mixing synchronous and asynchronous code - see Stephen Toub's last blog post Should I expose synchronous wrappers for asynchronous methods? For this reason, I think it's just cleaner to expose asynchronous operations as asynchronous APIs (and synchronous operations as synchronous APIs).
Update: If you do want synchronous code to call asynchronous code, then you can use the Task.WaitAndUnwrapException extension method in my AsyncEx library. However, you still have the problems mentioned in Stephen Toub's post, namely these:
You can deadlock if your library doesn't use ConfigureAwait(false) everywhere it can.
You can also deadlock if you run into the maximum number of threads in the thread pool.
(2) is not that common anymore, but (1) is a real possibility. It's regularly brought up by people who are just testing out async so they mix it with synchronous code.

Creating an async method in .NET 4.0 that can be used with "await" in .NET 4.5

I have a .NET project that uses C# in .NET 4.0 and VS2010.
What I would like to do is add some async overloads to my library to make doing async programming easier for users in .NET 4.5 with the await keyword. Right now the methods that are being overloaded are non-asynchronous. Also I don't want to use any async methods myself, just create new ones and make them available.
Is creating async methods in .NET 4.0 and VS2010 possible and if so, what should the .NET 4.0 async method look like?
Because I'm using VS2010 I don't have access to the "async" keyword so what needs to happen to emulate that behavior in .NET 4.0? For example does it need to return any particular type, and does any code need to happen inside the method to make the currently non-asynchronous code it is calling happen asynchronously?
As others have stated, you start by having a method return Task or Task<TResult>. This is sufficient to await its result in .NET 4.5.
To have your method fit in as well as possible with future asynchronous code, follow the guidelines in the Task-based Asynchronous Pattern document (also available on MSDN). It provides naming conventions and parameter recommendations, e.g., for supporting cancellation.
For the implementation of your method, you have a few choices:
If you have existing IAsyncResult-based asynchronous methods, use Task.Factory.FromAsync.
If you have another asynchronous system, use TaskCompletionSource<TResult>.
The simplest way to do this is to return a Task or a Task<T>. That will be enough.
However this only makes sense if your method really executes asynchronously.
I also recommend that you follow the usual pattern of naming them like AbcAsync ("Async" suffix). Your callers will not notice any difference to an async method created with C# 5 (because there is none).
Tip: Just adding async to the method does nothing. Your method will execute sequentially and return a completed task. Making the method return a task must serve a certain purpose - usually this is done because the method inherently executes asynchronously (like a web-service call or file IO).
If your method only contains computation but no IO (or only blocking IO) it is usually better not to make it async because you gain nothing doing that. Async methods do not always execute on a separate thread. If that last sentence surprised you, you may want to dig a little into this topic.
As long as you return a Task that completes somehow (whether in a thread or asynchronously), you would support the async model..
Having a Task execute asynchronously is another story. If you had access to the async keyword and the API you could simply base your method on async calls to other, already supplied async methods. But in this case, you have to hand-craft your async Tasks.
There might be better ways to do it, but the most elegant way I can see (and have used) is to utilize System.Threading.Tasks.TaskCompletionSource to construct a task, use Begin/End model of asynchronous methods to execute whatever you need to execute. Then, when you have the result on hand, post it to the previously constructed Task instance using your completion source.
It will certainly be asynchronous, just not as fancy as the ones in upcoming release.
Disclaimer: I'm no way near an expert on this. Just made some experiments on.

what is the main difference between .net Async and google go light weight thread

When calling runtime.GOMAXPROCS(1) in go the runtime will only use one thread for all your goroutines. When doing io your goroutines will yield and let the other goroutines run on the same thread.
This seem very similar to me to how the .net Async CTP feature is doing cooperative concurrency if you are not using background thread.
My question is which advantage or drawback could you think of one methode over the other.
Making value judgements is always a tricky thing so I'll highlight 3 differences. You decide whether they fall into the "pro" or "con" bucket.
While both Go and async allow you to write async code in a straightforward way, in .NET you have to be aware which part of your code is async and which one isn't (i.e. you have to explicitly use async/await keywords). In Go you don't need to know that - the runtime makes it "just work", there is no special syntax to mark async code.
Go design doesn't require any special code in standard library. .NET required adding new code to the standard library for every async operation, essentially doubling API surface for those cases e.g. there's new async http download API and the old, non-async http download API has to remain for backwards compatibility.
Go design and implementation is orders of magnitude simpler. A small piece of runtime code (scheduler) takes care of suspending goroutines that block on system calls and yielding to sleeping goroutines. There is no need for any special async support in standard library.
.NET implementation first required adding the aforementioned new APIs. Furthermore .NET implementation is based on compiler rewriting code with async/await into an equivalent state machines. It's very clever but also rather complicated. The practical result was that the first async CTP had known bugs while Go's implementation was working pretty much from the beginning.
Ultimately, it doesn't really matter. async/await is the best way to write async code in .NET. Goroutines are the best way to get that in Go. Both are great, especially compared to alternatives in most other languages.

Is it a best practice to call methods asynchronously by using delegates?

This msdn article is entitled "How to call a Visual C# method asynchronously".
The article says "Asynchronous calls are made by using delegates" to which I reply in my head "not necessarily, that's only one way to do it".
The matter-of-fact tone of the articles statement makes me wonder - Is it a best practice, or does MS consider it a best practice, to use delegates when making asynchronous calls?
Up to the current .NET version, asynchronous methods have typically been handled in separate background threads from the one you trigger them from, so it's been mostly essential to do it using a delegate that you can invoke in another thread.
However, with the recent C# Async CTP (which will probably be in C# 5.0 or another future version), the story is changed a little - it's not essential to use delegates, you can write code in a traditional imperative style, and the compiler will do most of the work for you. This might involve delegates, but not necessarily - the compiler does some clever tricks and writes a finite state machine which can be used to execute code asynchronously.
Yes, delegates are the way to call methods asynchronously. It is not best practice, that is how it is done. In .NET, you must use a delegate.
Somebody can tell me im wrong please but i've been under the impression at compile time a delegate is as good as a method, the purpose of a delegate being a signature definition. I can think of no other way of executing async code without a method even if its anonymous which becomes a method at compile time..

Categories

Resources