Different ways to create a thread - C#


SUBMITTED BY: emmek

DATE: May 4, 2022, 6:59 p.m.

FORMAT: C#

SIZE: 2.0 kB

HITS: 10337

  1. //Method with no parameter - ThreadStart Delegate
  2. Thread t = new Thread (new ThreadStart (TestMethod));
  3. t.Start();
  4. void TestMethod() {}
  5. //Method with a parameter - ParameterizedThreadStart Delegate
  6. Thread t = new Thread (new ThreadStart (TestMethod));
  7. t.Start(5);
  8. t.Start("test");
  9. void TestMethod(Object o) {}
  10. //lambda expression
  11. Thread t = new Thread ( () => TestMethod("Hello") );
  12. t.Start();
  13. void TestMethod(string input) {}
  14. //lambda expression for smaller thread methods
  15. new Thread (() =>
  16. {
  17. Console.WriteLine ("I'm running on another thread!");
  18. Console.WriteLine ("This is so easy!");
  19. }).Start();
  20. //anonymous methods C# 2.0
  21. new Thread (delegate()
  22. {
  23. Console.WriteLine ("I'm running on another thread!");
  24. }).Start();
  25. //Task Parallel Libray
  26. static void Main()
  27. {
  28. System.Threading.Tasks.Task.Factory.StartNew (Go);
  29. }
  30. static void Go()
  31. {
  32. Console.WriteLine ("Hello from the thread pool!");
  33. }
  34. //Generic Task class
  35. static void Main()
  36. {
  37. // Start the task executing:
  38. Task<string> task = Task.Factory.StartNew<string>
  39. ( () => DownloadString ("http://www.linqpad.net") );
  40. // We can do other work here and it will execute in parallel:
  41. RunSomeOtherMethod();
  42. // When we need the task's return value, we query its Result property:
  43. // If it's still executing, the current thread will now block (wait)
  44. // until the task finishes:
  45. string result = task.Result;
  46. }
  47. static string DownloadString (string uri)
  48. {
  49. using (var wc = new System.Net.WebClient())
  50. return wc.DownloadString (uri);
  51. }
  52. //Prior to TPL v4.0, Use ThreadPool.QueueUserWorkItem and asynchronous delegates
  53. //Example for ThreadPool.QueueUserWorkItem
  54. static void Main()
  55. {
  56. ThreadPool.QueueUserWorkItem (Go);
  57. ThreadPool.QueueUserWorkItem (Go, 123);
  58. Console.ReadLine();
  59. }
  60. static void Go (object data) // data will be null with the first call.
  61. {
  62. Console.WriteLine ("Hello from the thread pool! " + data);
  63. }

comments powered by Disqus