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..
Related
Is it possible to define and call method asynchronously in the same thread as the caller?
Suppose I have just one core and I don't want threading management overhead with like 100 threads.
Edit
The reason I ask is nodejs model of doing things - everything on one thread never blocking anything, which proved to be very efficient, which made me wonder if same stuff possible in C# (and I couldn't achieve it myself).
Edit2 Well, as noted in comments node isn't single-threaded after all (however simple load test shows, that it uses just one core...), but I think what makes it so efficient is implicit requirement to write only non-blocking code. Which is possible in C#, except not required:) Anyway, thanks everyone...
More info in
this SO post and even more in this one
It's not really clear exactly what context you're talking about, but the async/await feature of C# 5 already helps to support this sort of thing. The difference is that whereas in node.js everything is forced to be single threaded by default (as I understand it; quite possibly incorrectly given the links in the comments), server-side applications in .NET using asynchrony will use very few threads without limiting themselves to that. If everything really can be served by a single thread, it may well be - if you never have more than one thing to do in terms of physical processing, then that's fine.
But what if one request comes in while another is doing a bit of work? Maybe it's doing just a small amount of encryption, or something like that. Do you really want to make the second request wait for the first one to complete? If you do, you could model that in .NET fairly easily with a TaskScheduler associated with a single-thread thread-pool... but more commonly, you'd use the thread-pool built into .NET, which will work efficiently while still allowing concurrency.
First off, you should make sure you're using .NET 4.5 - it has far more asynchronous APIs (e.g. for database and file access) than earlier versions of .NET. You want to use APIs which conform to the Task-based Asynchronous Pattern (TAP). Then, using async/await you can write your server-side code so that it reads a bit like synchronous code, but actually executes asynchronous. So for example, you might have:
Guid userId = await FetchUserIdAsync();
IEnumerable<Message> messages = await FetchMessagesAsync(userId);
Even though you need to "wait" while each of these operations talks place, you do so without blocking a thread. The C# compiler takes care of building a state machine for you. There's no need to explicitly write callbacks which frequently turn into spaghetti code - the compiler does it all.
You need to make sure that whatever web/web-service framework you use supports asynchrony, and it should just manage the rest, using as few threads as it can get away with.
Follow the two links above to find out more about the asynchrony support in C# 5 - it's a huge topic, and I'm sure you'll have more questions afterwards, but when you've read a bit more you should be able to ask very specific questions instead of the current broad one.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Why does asynchronous delegate method require calling EndInvoke?
Is Delegate.EndInvoke() really necessary?
Working on a multi-threaded application at the moment and when raising an event instead of doing the normal handler.Invoke(); I am experimenting with handler.BeginInvoke();. Both work fine. However, for BeginInvoke I am using null for the last two arguments because there needs not be a callback and since there is no callback, there is definitely no need for data to be passed to a non-existent callback.
Because of this, I am not calling EndInvoke at all. But the application seems to.. work perfectly? I read and people said there would be leaks which may be occurring but I am just not noticing.
I'm curious though, what exactly does EndInvoke do? Do I really need to make a callback just to call EndInvoke and that's it? Also, why does EndInvoke take an IAsyncResult argument? I can just pass null for that right because there is no extra data being passed to the callback, correct? But still, I'm wondering, why, if there was extra data, would it need to be passed to EndInvoke? What is it doing with that parameter? I want to know how it works.
I checked the .NET Reflector but I couldn't find where EndInvoke was actually defined. In EventHandler (which is what I'm using) all it showed was the method header.
Thanks.
The main practical concerns are deterministically cleaning up a wait handle resource (if you chose to create the handle by referencing it) and making sure that Exceptions are propagated properly.
That said, what I would recommend is to move away from the slightly schizophrenic asynchronous pattern in the earlier .NET framework and use TPL, which has a much cleaner continuation model. The TPL even has some nice wrapping functionality to help deal with the older Begin/End style of calling:
http://msdn.microsoft.com/en-us/library/dd997423.aspx
As was mentioned in one of the referenced articles, if you're invoking a delegate in a fire-and-forget fashion, you probably should use ThreadPool.QueueUserWorkItem instead. Then you won't have to worry about cleaning up with EndInvoke.
According to MSDN, you ought to always call EndInvoke no matter what:
No matter which technique you use, always call EndInvoke to complete your asynchronous call.
So take that for what it's worth. I assume it's futureproofing.
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.
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)
I was told that Invoke() is similar to normal method calling... so why would people choose to use Invoke and not normal method calling?
I tried to search online regarding the issue, what i get is the advantages of using BeginInvoke(), but what are the advantages of using Invoke()?
Use BeginInvoke when you want to call the delegate asynchronously (on a thread drawn from the thread pool) and Invoke if you want to call it synchronously.
It's worth noting first that we have to have something like .Invoke() as the meeting-point between languages. Just as what is int to C# and Integer to VB.NET is System.Int32 to both of them, and to any other CLR language; so too we have Invoke() which any CLR language can offer access to, and which they can then provide additional syntactic sugar in a means suitable for their syntax (most would consider heavily VB style conventions in C# or heavily C# style conventions in VB to be syntactic vinegar; sugar always has to match the rest of the language as best it can).
This sugar added, why not use it all the time? Some people will sometimes want to be clear that they are dealing with a delegate. Some just won't use it; I mostly don't. Like all syntactic sugar, the advantages and disadvantages are matters of clarity rather than correctness (indeed, look at a call to x.Invoke() in reflector and you'll see that it as x() because reflector doesn't know which you used).
One reason is if you've gotten your method signature through reflection and you dynamically want to instantiate a function, Invoke() is the way you'd do that.
In order to change, for example, the thread executing something.
Note that any UI control shall and can alweays only be manipulated from the thread that created it (message pump, actually). So, if another thread is manipulating the control (synchronously from that other threads point of view) then BeginInvoke would be additional overhead, but Invoke is fine (ESPECIALLY because at least in WPF there is a shortcut herere for multiple invoke sequences that make it faster to execute internally).
I guess you already understand what a delegate is, what is for, and why is useful.
If I have a deletegate named "MyDelegate", I can do "MyDelegate(foo);" or "MyDelegate.Invoke(foo);" , but I always use the second one so I could easily see when I review the code, that is actually a delegate and not a method. There is no internal difference.