Skip to content

Instantly share code, notes, and snippets.

@opdo
Last active September 24, 2019 16:50
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 opdo/544defce036a6d56f47c12fd4e6702c5 to your computer and use it in GitHub Desktop.
Save opdo/544defce036a6d56f47c12fd4e6702c5 to your computer and use it in GitHub Desktop.
DemoThread.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace TestThread
{
class Program
{
// Khai báo 1 thread
static Thread thread;
static void Main(string[] args)
{
// khởi tạo thread
thread = new Thread(ThreadFunc);
thread.IsBackground = true;
while (true)
{
// in menu
PrintMenu();
// lựa chọn
switch (Console.ReadLine())
{
case "1":
// start thread
// kiểm tra thread đang start hay ko
if (!thread.IsAlive) thread.Start();
else
{
Console.WriteLine("Thread dang running, khong can start lai");
Console.ReadLine();
}
break;
case "2":
// resume hoặc pause
if (!thread.IsAlive)
{
Console.WriteLine("Vui long start thread truoc khi pause/ resume");
Console.ReadLine();
}
else
{
if (thread.ThreadState.HasFlag(System.Threading.ThreadState.Suspended)) thread.Resume();
else if (thread.ThreadState.HasFlag(System.Threading.ThreadState.Background)) thread.Suspend();
}
break;
case "3":
if (thread.IsAlive) thread.Abort();
else
{
Console.WriteLine("Khong co thread dang running");
Console.ReadLine();
}
break;
default:
if (thread.IsAlive) thread.Abort();
return;
break;
}
}
}
private static void PrintMenu()
{
Console.Clear();
Console.WriteLine("TEST THREAD");
Console.WriteLine("1: Start");
Console.WriteLine("2: Pause/Resume");
Console.WriteLine("3: Close thread");
}
// hàm mà thread chạy
public static void ThreadFunc()
{
int time = 0;
do
{
Thread.Sleep(1000);
time++;
Debug.WriteLine("Thread is running in " + time + " sec(s)");
} while (true);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment