5

I am trying to learn C#! I am most familiar with Java between programming languages! Just now I am trying to understand Task's! Is there something like Task in Java?

What are the differences between Task's and threads? What does Task offer that threads can not do? Basically why do we need Task's?

River
  • 8,585
  • 14
  • 54
  • 67
Govan
  • 2,079
  • 4
  • 31
  • 53
  • I think this http://stackoverflow.com/questions/9018159/is-there-an-equivalent-in-c-sharp-to-this-java-code gives you some idea. – Vinay Aug 18 '12 at 11:26
  • possible duplicate of [Equivalent of Task Parallel Library in Java](http://stackoverflow.com/questions/4117579/equivalent-of-task-parallel-library-in-java) – Fluffeh Aug 19 '12 at 13:25

5 Answers5

9

I'd say the closest 1:1 class is Future<T> or CompletableFuture<T>. CompletableFuture has some extra chaining methods similar to those in Task<T> in C#.

Apparently in early versions of the Task Parallel Library (C#) Task<T> was called Future<T> (http://www.nedstoyanov.com/promises-and-futures/)

Mingwei Samuel
  • 2,917
  • 1
  • 30
  • 40
5

The Fork/Join framework introduced in Java 7 is probably the closest thing:

http://docs.oracle.com/javase/tutorial/essential/concurrency/forkjoin.html

Dan
  • 1,030
  • 5
  • 12
2

Task is something you want to do , thread is something that executes your task

e.g. Web server that starts a new thread for each request

 class ThreadPerTaskWebServer {
    public static void main(String[] args) throws IOException {
        ServerSocket socket = new ServerSocket(80);
        while (true) {
            final Socket connection = socket.accept();
            Runnable task = new Runnable() {
                public void run() {
                    handleRequest(connection);
                }
            };
            new Thread(task).start();
        }
    }
}
Amit Deshpande
  • 19,001
  • 4
  • 46
  • 72
  • Is it possible that many threads to execute the same task? Is it possible to divide a task to some parts and every thread is being responsible to do a part of a task? – Govan Aug 18 '12 at 11:30
  • Copied fro JCIP >Ideally, tasks are independent activities: work that doesn’t depend on the state, result, or side effects of other tasks. Independence facilitates concurrency, as independent tasks can be executed in parallel if there are adequate processing resources. For greater flexibility in scheduling and load balancing tasks, each task should also represent a small fraction of your application’s processing capacity. – Amit Deshpande Aug 18 '12 at 11:32
1

If you look at the documentation it states that tasks is the preferred way of doing multithreaded programming:

More efficient and more scalable use of system resources.

Behind the scenes, tasks are queued to the ThreadPool, which has been enhanced with algorithms (like hill-climbing) that determine and adjust to the number of threads that maximizes throughput. This makes tasks relatively lightweight, and you can create many of them to enable fine-grained parallelism. To complement this, widely-known work-stealing algorithms are employed to provide load-balancing.

More programmatic control than is possible with a thread or work item.

Tasks and the framework built around them provide a rich set of APIs that support waiting, cancellation, continuations, robust exception handling, detailed status, custom scheduling, and more.

msdn

So tasks is actually threads, but with an easier interface. You can also take a look at this question which basically asks the same thing as you do: SO Question

Community
  • 1
  • 1
Daniel Figueroa
  • 10,348
  • 5
  • 44
  • 66
  • Yeah I read some of the documentations! But Steel I don't know when I should think hmm here I can use Task instead of a thread! Is the Task in C# is the same which the android platform is using? – Govan Aug 18 '12 at 11:27
  • 1
    Are you thinking about AsyncTask? The android platform uses Java so no, they're not the same. For you second question the answer that @Amit Deshpande gave you should suffice. – Daniel Figueroa Aug 18 '12 at 11:31
1

What are the differences between Tasks and threads? What does Task offer that threads can not do? Basically, why do we need Tasks?

Threads are a mechanism for parallelization and Tasks are a mechanism for synchronization. In simpler terms, a thread is a worker, a task is a unit of work. Often the same worker can execute multiple units of work not in parallel though. It can achieve a great level of efficiency by prioritizing tasks and managing context which entirely done by .NET behind the scene.

Think of it this way. You, as a developer, arrive to work and you have two tickets to comlete. One ticket requires clarification from a project manager. So you send an email to the project manager asking for more information.

There is no really need to wait for a reply, you can start working on the second ticket. You are still a single thread (a single worker) but you are managing two tasks - two units of work. While you are working on the second ticket, the product manager responds with an answer. You can choose to switch context and return to executing Ticket 1 or you can wait till Ticket 2 is complete and only then switch the context back to ticket 1.

In an alternative scenario, you can pick a teammate and assign her Ticket 2. In this case, you are achieving genuine parallelization but you get two workers involved: yourself and your coworker.

In .NET spawning, a new thread is computationally very expensive. It is a good practice to use tasks whenever long-running operations are I/O bound such as reading from DB for example. It is better to use threads for CPU bound heavy operations such as heavy mathematical computations.

var productsTask = GetItemtsAsync(odredId) // dispatch call to DB
var userTask = GetUserInfoAsync(userId) // dispatch another call to DB

// wait until both calls are completed, their order is irrelevant
// and it is fully managed by the runtime
Task.AwaitAll(productsTask, userTask)

// now we have enough data to generate an invoice 
// (this is all done on one thread)
var invoice = GenerateInvoice(productsTask.Result, userTask.Result)

By running DB calls in separate threads, you will make your code slower, since you still have no control over how long DB calls run and in addition, you will spend time on creating new threads (these would be very expensive operations, memory-wise and CPU cycle-wise)

Note: the code below accomplishes the same thing as the code snippet above but it is more elegant. Using .Result is not advisable in certain scenarios

var productsTask = GetItemtsAsync(odredId) // dispatch call to DB
var userTask = GetUserInfoAsync(userId) // dispatch another call to DB

var invoice = GenerateInvoice(await productsTask, await userTask)
AstroSharp
  • 1,872
  • 2
  • 22
  • 31