Tag: thread

Rolling multiple balls as multiple threads

In this example, we roll multiple balls as multiple threads. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Media; using System.Drawing.Drawing2D; using System.Threading; using System.Collections; namespace howto_bouncing_ball { // Each thread must have its own data // otherwise all threads will use // same x,y values

Background threads

We can also declare a thread as background thread by specifying IsBackground property to true using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; namespace ThreadPrograms { class Program { static void Main(string args) { var t1 = new Thread(ThreadMain) { Name = "MyNewThread", IsBackground = true}; t1.Start(); Console.WriteLine("Main thread ending now.");

Passing data to threads

There are two ways to pass data to threads. The first one is using a structure. The second one is using a class. Passing data using structure: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; namespace ThreadPrograms { public struct Data { public string Message; } class Program { static void

Thread ordering

There is no guarantee that which thread will execute first. In the following program, any thread can execute first depending on how operating system schedule using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; namespace ThreadPrograms { class Program { static void Main(string args) { var t1 = new Thread(MyThread1); var t2

Creating thread with lambda expressions

Instead of defining a separate method for thread to execute, we can use lamda expression notation to execute the thread. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; namespace ThreadPrograms { class Program { static void Main(string args) { var t1 = new Thread(() => Console.WriteLine("Running in a thread, id: {0}",

Creating a simple thread

To create a thread, we simple call one argument constructor of Thread class and pass as argument the function, we want to execute as thread. In below example, the function MyThread() is passed to the Thread class constructor and it executes as a thread: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using