C# Task.ContinueWith() vs java?

Viewed 882

in C# , Task class has ContinueWith method, when the task runs to complete status, the ContinueWith method will be invoked, and in JAVA, is there some methods like ContinueWith ?

I know the guava listenablefuture, but it use a new thread to wait the 'task' to complete, is it equal to C# ContinueWith?

and JAVA 8 CompletableFuture whenComplete has the same effect, so what's the difference in C# ContinueWith listenablefuture CompletableFuture?

thank you!

1 Answers

A Task in .Net and a CompletableFuture in Java accomplish a very similar purpose. They provide a reference to something that is executing in a different thread (a TaskScheduler in .Net or an Executor in Java), with the ability to wait for the result and/or perform different actions on completion.

There are a couple of differences between Task.ContinueWith and CompletableFuture.whenComplete. For one, the function passed into the .Net version takes the Task itself as an argument, requiring an additional step to get its result (or to propagate downstream exceptions if necessary). The function passed into Java version takes the result of the task as an argument.

The other significant difference is the thread on which the continuation task will run. In .Net, it will by default run on a different thread from the main task. In Java, it will by default run on the same thread as the main task. These default actions can be overridden in both cases.

Related