Question: What is parallel processing in C#?
|
Answer: Parallel processing in C# involves executing multiple tasks concurrently to improve performance
by utilizing multiple CPU cores. It allows for better utilization of system resources and can lead to
significant performance improvements for CPU-bound tasks.
|
Question: What is the Task Parallel Library (TPL) in C#?
|
Answer: The Task Parallel Library (TPL) is a set of APIs in .NET Framework and .NET Core that
simplifies parallel programming in C#.
It provides high-level constructs such as tasks, parallel loops, and parallel LINQ (PLINQ) to facilitate
writing parallel and asynchronous code.
|
Question: What is a task in the Task Parallel Library (TPL)?
|
Answer: A task in the Task Parallel Library represents an asynchronous operation that can
run concurrently with other tasks.
It is used to encapsulate units of work that can be executed asynchronously, allowing parallel execution
and efficient utilization of system resources.
|
Question: What is the difference between 'Task' and 'Thread' in C#?
|
Answer: A 'Task' in C# represents an asynchronous operation that can run concurrently with other tasks
and is managed by Task Parallel Library.
'Threads', on the other hand, are lower-level constructs provided by the operating system
for concurrent execution of code. Tasks are more lightweight and provide higher-level abstractions
compared to threads, making them easier to work with for parallel programming.
|
Question: How do you create and start a Task in C#?
|
Answer: Tasks can be created and started using the Task.Run() method or by directly instantiating
the Task class and calling its Start() method.
Additionally, async/await keywords can be used to create and start tasks asynchronously,
allowing for more concise and readable code. Example:
int[] numbers = Enumerable.Range(0, 1000000).ToArray();
string result = (time < 18) ? "Good day." : "Good evening.";
// Use Task.Run to start a task that computes the sum of numbers
Task task = Task.Run(() =>
{
long total = 0;
for (int i = 0; i < numbers.Length; i++)
{
total += numbers[i];
}
return total;
});
// Await the task to retrieve the result
long result = await task;
Console.WriteLine($"Sum is {result}");
|
Question: What is data parallelism in the context of parallel processing?
|
Answer: The data parallelism involves dividing a task into smaller subtasks that can be executed
concurrently on different CPU cores, typically operating on different pieces of data in parallel.
It allows for efficient parallel execution by processing independent data items concurrently.
|