Prep Asynchronous Tasks & Multi-threading

  1. What is multi-threading? What is asynchronous? What's the difference?
    Multi-threading is the ability of a computer to complete multiple tasks (jobs) concurrently. This is done using multiple processors or cores along with an operating system that supports multi-threading. Think of "threads" as multiple workers and think of a task as "jobs" to be done.

    Asynchronous processes are the ability to do two tasks at the same time.
  2. Explain in laymen terms the difference between an asynchronous call and a multi-threaded call using breakfast as an analogy.
    You are a cook assigned to make toast and eggs for breakfast:

    Synchronous: I start the toast, when it is complete, I start the eggs. Then serve.

    Asynchronous: I start the toast and cook the eggs. Then serve.

    Multi-threading: I hire two cooks, one which starts the toast and the other which starts the eggs. Each can start and end at their respective times. Then serve.

    Tasks are about jobs (cooking toast/eggs) whereas multi-threading is about workers used to complete that task. An asynchronous task is one type of job wherein the task can be started and until complete, control is handed off elsewhere, only to be returned to later, exactly where it had left off.
  3. What is the most common misconception about asynchronous processes?
    That they create a thread. They do not, they remain on the same thread they originated on, coming back only after they have completed their task.
  4. Write code to create and execute 3 different threads.
    • Parallel.Invoke(
    •      ThreadProcess1,
    •      ThreadProcess2,
    •      ThreadProcess3
    • );

    • static void ThreadProcess1()
    • {
    •    Console.WriteLine($"Method 1, Thread={Thread.CurrentThread.ManagedThreadId}");
    • }

    • static void ThreadProcess2()
    • {
    •    Console.WriteLine($"Method 2, Thread={Thread.CurrentThread.ManagedThreadId}");
    • }

    • static void ThreadProcess3()
    • {
    •    Console.WriteLine($"Method 3, Thread={Thread.CurrentThread.ManagedThreadId}");
    • }
  5. Write code to create and execute 3 different threads using a single method, an inline delegate, and using a lambda expression.
    • Parallel.Invoke(
    •      NormalAction, // Invoking Normal Method
    •      delegate () // Invoking an inline delegate
    •      {
    •         Console.WriteLine($"Method 2, Thread=                         {Thread.CurrentThread.ManagedThreadId}");
    • },
    •      () => // Invoking a lambda expression
    •      {
    •         Console.WriteLine($"Method 3, Thread=            {Thread.CurrentThread.ManagedThreadId}");
    •      }
    • );
  6. Write code which would use multi-threading to loop through and process all files within a given directory, each on their own thread.
    string[] fileEntries = Directory.GetFiles(targetDirectory);

    • Parallel.For(0, fileEntries.Length, i =>
    • {
    •      ProcessFile(fileEntries[i].ToLower());
    • });

    • public static void ProcessFile(string path)
    • {
    •      Console.WriteLine("Processed file '{0}' on managed thread id #{1}", path, Thread.CurrentThread.ManagedThreadId);
    • }
  7. What can be used in replace of complicated parallel multi-threading code? How do we use it?
    Use of the Parallel.Invoke method using the System.Threading.Tasks assembly.

    We pass Actions to it the Parallel.Invoke() method, each action being a static void method will work as an Action.
  8. Write an asynchronous API call for GetBooks() which will return a list of Book objects.
    • [HttpGet]
    • public async Task<IActionResult> GetAll()
    • {
    •      var model = await _db.Books.ToListAsync();
    •      return Ok(model);
    • }
  9. Write an asynchronous API call for Get(int? id) which will return a single Book object.
    • [HttpGet]
    • [Route("{id}", Name = "Get")]
    • public async Task<IActionResult> Get(int? id)
    • {
    •      if (id == null)
    •         return BadRequest();

    •      var result = await _db.Books.FindAsync(id);
    •      if (result == null)
    •         return NotFound();
    •      else
    •         return Ok(result);
    • }
Author
mateotete
ID
351501
Card Set
Prep Asynchronous Tasks & Multi-threading
Description
Questions on asynchronous processing and multi-threading.
Updated