• Profile
  • Resume
  • Portfolio
  • Blog
Avatar

Nelson Silva

A human. Being. Coffee lover.

Blog

I Write My Thoughts Here

Thread Class in C#

January 18, 2022 C#

In this post, you will learn how to work with the Thread class so that you can use that same knowledge and thus evolve.

  • this class (belonging to the System.Threading library) allows the creation/control of a certain process and it is possible to define its priority and obtain its status;
  • the thread is basically a task.
Thread (object).Start() Starts the particular thread that was instantiated
Thread (object).Join() Block the starting (calling) thread until the current thread ends
Sleep() Suspend the current thread for the specified time (time in milliseconds)
using System;
using System.Threading;

namespace Base {
  class ThreadClass {
    private Thread thread;

    public void Run() {
      thread = new Thread(ExecuteThread);
      thread.Start();

      for (int index = 1; index <= 5; index++) {
        Console.WriteLine($"Run() #{index}");
        Thread.Sleep(1000);
      }

      Console.WriteLine("The Run() thread terminated.");

      thread.Join();

      Console.WriteLine("The ExecuteThread() thread terminated.");
    }

    private void ExecuteThread() {
      for (int index = 1; index <= 10; index++) {
        Console.WriteLine($"ExecuteThread() #{index}");
        Thread.Sleep(1000);
      }
    }
  }
}

/*
  Run() #1
  ExecuteThread() #1
  Run() #2
  ExecuteThread() #2
  Run() #3
  ExecuteThread() #3
  Run() #4
  ExecuteThread() #4
  Run() #5
  ExecuteThread() #5
  The Run() thread terminated.
  ExecuteThread() #6
  ExecuteThread() #7
  ExecuteThread() #8
  ExecuteThread() #9
  ExecuteThread() #10
  The ExecuteThread() thread terminated.
*/

Don’t forget to watch the video and you can always read this post in Portuguese.

Happy coding!

Previous Next

Categories

  • Announcements
  • Python
  • C#
  • Java
  • Go

Latest Posts

  • for Loop in Go
    May 5, 2022
  • Switch in Go
    May 4, 2022
  • Comparison Operators in Go
    May 3, 2022
+351913416022
contact@nelsonsilvadev.com
Porto, Portugal
Nelson Silva © 2022 All Rights Reserved