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

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?

Related

Asynchronous delegates: performance in modern .NET world

There is a legacy project. There are a lof of Asynchronous delegates and code like this:
IAsyncResult result = startDelegate.BeginInvoke(param1,
param2,
new AsyncCallback(CallbackMethod),
null);
or just completely parameterless calls
like
IAsyncResult result = startDelegate.BeginInvoke(CallbackMethod,null);
The main purpose of desired refactoring is: performance. Many places in the project has been optimized a lot and now it's time for async stuff.
From performance point of view: is there any sense to migrate from Async delegates calls to:
ThreadPool.QueueUserWorkItem for parametless calls
 BackgroundWorker to report progres to GUI (now GUI subcribes to events in async code)
Rewrite some parts to async await?
so, general question: how bad (or not bad) from performance point of view Async delegates in compare with 1)-3) above?
The main purpose of desired refactoring is: performance.
You almost certainly won't see noticeable performance gains from changing this. However, there are two major benefits for replacing Delegate.BeginInvoke calls:
Maintainability. async/await is the style of asynchronous programming that is most maintainable.
Portability. Last I checked, .NET Core doesn't support Delegate.BeginInvoke, so if you ever move from .NET Desktop Framework to .NET Core, you'll need to change this code. Side note: there are some pretty good performance benefits just from migrating to .NET Core.
If you do choose to remove the calls to BeginInvoke, I recommend using Task.Run. It's a modern solution.

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.

C++ std::async vs async/await in 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)

What are some strategies for working multi-threading into libraries?

I'm in the process of writing a library that deals with long-running tasks like file downloading and processing large amounts of text. I want to multi-thread this library so that these tasks won't freeze up the applications that use them.
Do you have any advice for doing so in a structured manner, or specific classes I should use/avoid? I was thinking of using the IAsyncResult interface: http://msdn.microsoft.com/en-us/library/system.iasyncresult.aspx, or perhaps some BackgroundWorkers.
so that these tasks won't freeze up the applications that use them.
If this is your goal, you should look into the standard asynchronous programming patterns in the framework.
If your library is targeting .NET 4, have it return Task and Task<T>, as this will ease transition into the async support coming in the next release of C# and VB.NET. This also has the very nice addition of allowing synchronous usage with no extra work on your part, since the user can always just do:
var result = foo.BarAsync().Result; // Getting Task<T>.Result blocks, effectively making this synchronous
If you're targeting .NET 3.5 or earlier, you should consider using the Event-based asynchronous pattern, as it is used in more of the current APIs than the APM.

Categories

Resources