Skip to content

Instantly share code, notes, and snippets.

@SkymanOne
Created August 26, 2021 21:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SkymanOne/bc7fe9727a80f512746880ca8d506fd8 to your computer and use it in GitHub Desktop.
Save SkymanOne/bc7fe9727a80f512746880ca8d506fd8 to your computer and use it in GitHub Desktop.
Mini multithread application example
using System;
using System.Threading;
namespace threadTest
{
class Program
{
static void Main(string[] args)
{
//Let's create a dedicated thread to demmonstarte that the whole process can be done inside another thread
Thread thread = new Thread(FakeListening);
thread.Start();
}
//this functions will imitate some long process which can be finished at some
//For example: listinging to tcp client's new messages
//The connection can be closed by a client later or some error occurs
private static void Test(int i) {
while (true) {
Console.WriteLine($"Message from {i}");
int secs = i * 100;
//put thread on sleep so the messages can be distinguished between different threads
Thread.Sleep(secs);
Console.WriteLine($"Thread {i} slept {secs} secs");
Random rnd = new Random();
if (rnd.Next(2) == 1) {
break;
}
}
Console.WriteLine($"Thread {i} finishes its job");
}
//let's spawn multiple threads each runs some function with different paramaeters
private static void FakeListening() {
while (true) {
Random rnd = new Random();
Thread thread = new Thread(() => Test(rnd.Next(1, 100)));
thread.IsBackground = true;
thread.Start();
//sleep the thread to give some time for console to render messages
Thread.Sleep(2000);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment