Hot answers tagged

111

What Color Is Your Function? You may be interested in Bob Nystrom's What Color Is Your Function1. In this article, he describes a fictional language where: Each function has a color: blue or red. A red function may call either blue or red functions, no issue. A blue function may only call blue functions. While fictitious, this happens quite regularly in ...


82

You are right there is a contradiction here, but it is not the "best practices" being bad. It is because asynchronous function does essentially different thing than a synchronous one. Instead of waiting for the result from its dependencies (usually some IO) it creates a task to be handled by the main event loop. This is not a difference which can be well ...


24

As I understand it, asking for the Task's value in this manner will block code execution until the value from the awaited method is returned, effectively making this a synchronous call. Not quite. When you call await db.Departments.FindAsync(id) the task is sent off and the current thread is returned to the pool for use by other operations. The flow of ...


22

The only difference between the two is the synchronization used in StringBuffer. The overhead of synchronization is not huge in the grand scheme of things, but it is significant relative to the StringBuilder methods that don't have them. The JVM is doing work that it wouldn't otherwise have to do--especially with only one thread, etc. If your code works ...


20

Accoding to an Anders Hejlsberg interview for Channel 9 about Asynchronous Programming async/await in C# takes inspiration on async worflows in F#. In case you don't know, Anders Hejlsberg is the lead architect of C#, and has also worked in other languages including TypeScript. According to Don Syme, on his blog, F# async workflows take inspiration from ...


17

I think you're getting a few things confused, here. What you're asking for is already possible using System.Threading.Tasks, the async and await in C# 5 are just going to provide a little nicer syntactic sugar for the same feature. Let's use a Winforms example - drop a button and a textbox on the form and use this code: private void button1_Click(object ...


17

When Node.js is described as "non-blocking", that specifically means that its IO is non-blocking. Node uses libuv to handle its IO in a platform-agnostic way. On Windows, it uses IO completion ports, on Unix, it uses epoll/kqueue/select/etc. So, it makes a non-blocking IO request (which may have a background thread monitoring, but this is never exposed to ...


17

One issue I see using Task.WhenAll is that it does not return results But it does return the results. They'll all be in an array of a common type, so it's not always useful to use the results in that you need to find the item in the array that corresponds to the Task that you want the result for, and potentially cast it to its actual type, so it might not ...


16

The async keyword allows the method to use the await syntax within its definition. I can await on any method that returns a Task type regardless of whether it's an async method. void is a legal (albeit discouraged) return type for an async method, so why wouldn't it be allowed? From the outside, async isn't enabling anything you couldn't do without it. ...


15

I really hate that none of the examples show how it’s possible to wait a few lines before awaiting the task. Consider this. Foo foo = await getFoo(); Bar bar = await getBar(); Console.WriteLine(“Do some other stuff to prepare.”); doStuff(foo, bar); This is the kind of code the examples encourage, and you’re right. There’s little sense in this. It does ...


14

So, something's been bugging me about the new async support in C# 5: The user presses a button which starts an async operation. The call returns immediately and the message pump starts running again - that's the whole point. So the user can press the button again - causing re-entrancy. What if this is a problem? Let's start by noting that this is already a ...


14

Unfortunately, the answer is, "it depends." It would be easy for you to write a small program to empirically determine the times of both async and sync reads. It will depend on lots of factors. Are they stored on spinning disks, SSD, or a network drive? What kind of CPU are you using? How many sockets/cores? Are you running in an VM or bare metal? Are ...


13

The async and await keywords will not make your application more responsive on their own. They simply make the calling and handling of methods that return Task objects more convenient. In order to make async/await actually use background threads, you will need to combine with the usage of things like: Task.Start() - Starts a given task using the ...


13

In general, any function that does networking or uses timers to do things over a period of time will be asynchronous. If the function takes a callback, you can look at what the callback is used for and usually it will be obvious whether is is asynchronous or not. If the function does not offer a callback, then it has no way of communicating asynchronous ...


12

As those get increasingly wait-based-sluggish — in the order of the above list — the need for making the operation asynchronous will come along... Your reasoning is "requirements in the future might change, so let's design for them now". Smart. But don't stop there. What about error handling? Sure, some implementations of this interface might throw an ...


11

I think you misunderstand the await call. What async and await do is allow the thread you are executing on (not just the main thread) to continue working. The mechanism that supports this is called a continuation. So instead of the thread blocking (waiting) for IO, it can be execute other tasks. When the task in the await completes, the thread will ...


10

You will be able to accomplish your task using BackgroundWorker. It is a well known class, and many people have used it. The new C# 5 async and await keywords basically just make it easier to write readable asynchronous code. There may be fewer tutorials and examples of how to accomplish various tasks with these keywords rather than BackgroundWorker. ...


10

The sole purpose of the async keyword is to make await within the body of that function a keyword. This is needed so that adding the await functionality did not break existing code. Microsoft decided to make use of await an opt-in option. For a function that is not marked async you can define a variable named await with no issue. Hence async is not part of ...


10

C#'s Task is somewhere halfway between Java's Future and CompletableFuture. The Result property is equivalent to calling get(), ContinueWith() does the things the massive array of continuation functions on CompletableFuture does (add some Task.WhenAny and Task.WhenAll in there). But complete(T) has no equivalent (use a TaskCompletionSource), nor does cancel()...


9

Async has 3 main advantages: It lowers CPU utilization. This could be useful if you are also doing CPU-heavy operations with data you just read. Using some kind of async infrastructure makes the code easy to paralelise. Especially if you are reading lots of files. By sending multiple read-write requests to OS, OS and HW can re-order those operations to be ...


9

Your question is already answered in the SO question you linked. The purpose of async/await is to make it easier to write code in a world with many high latency operations. The vast majority of your operations are not high latency. When WinRT first came out, the designers were describing how they decided which operations were going to be async. They ...


9

ASP.Net that does not use the Task Parallel Library (TPL) is limited in the number of requests it can handle concurrently by the number of threads in a thread pool. ASP.Net that uses the TPL is limited by the CPU/memory/IO of the machine handling requests. The Task Parallel Library (TPL) does not consume threads in the way you seem to think it does. Tasks ...


9

Are you aiming at making a general-purpose Javascript to C automatic translator (that is, a compiler from Javascript to C)? This is quite challenging and will take you several years of work, in particular if you want to make an efficient Javascript to C compiler (something which won't be much slower than most current Javascript implementations) Notice that ...


9

I feel that c# has become a very wordy language and I'm not happy to have to code in the async style like this. Oh, but that is not wordy at all. You are not writting something like this: client.GetAsync("http://www.nzherald.co.nz/").Then ( response => response.Content.ReadAsStringAsync().Then ( pageContents => { ...


8

It's never absolutely necessary for a controller to be async. Calls to controller methods will eventually return. However, it might be desirable to hand off a long-running task to a thread, so that the web server is not blocked for a long period of time. I wouldn't bother making every controller asynchronous. There is some overhead involved in creating ...


7

This is a fascinating question. The most interesting take on it is, in my view, the approach adopted in Clojure and explained in this video: http://www.infoq.com/presentations/Value-Identity-State-Rich-Hickey Basically the "solution" proposed is as follows: You write most of your code as classic "pure" functions with immutable data structures and no side ...


7

Don't make things lazy that don't need to be. If you know that Payer will be needed the grand majority of the time then there is no value in making the loading of Payer be lazy. Instead make it eager on constructions of Order. Lazyness is only of value for expensive things that may not happen or don't need to happen. As a side note when doing a lazy load ...


7

You have missed the point of async/await It wasn't created to frustrate developers with deadlocks. It was created to free up Processing power while we wait for a non CPU based task to complete. The lack of synchronisation context in dotnetcore might save you from unexpected deadlocks, but it also means you have to worry about thread starvation. Everytime ...


Only top voted, non community-wiki answers of a minimum length are eligible