Simple threading example in C#

Threading example – idea is that you can copy and paste this code in to get you started quickly.

using System;
using System.Threading;

class ThreadJobClass
  {
    public bool fetching = false;
    public bool fetched = false;
    public string value = null;

    protected int rand;

    public ThreadJobClass(int _rand)
    {
      rand = _rand;
    }

    public void run()
    {
      try
      {
        fetching = true;
        Console.WriteLine("Fetching from " + rand.ToString());
        Thread.Sleep(rand);
        value = rand.ToString();
      }
      catch (Exception e)
      {
        Console.WriteLine(e);
      }
      finally
      {
        fetching = false;
        fetched = true;
      }
    }
  }

  class Program
  {
    static void Main(string[] args)
    {
      var insts = new List<ThreadJobClass>();
      var my_random = new Random();
      for (var i = 0; i < 5; i++)
      {
        var rand = my_random.Next(2000);
        var inst = new ThreadJobClass(rand);
        insts.Add(inst);
      }
      var num_fetched = 0;
      var num_fetching = 0;
      var max_fetching = 2;
      while (num_fetched < insts.Count)
      {
        foreach (var inst in insts)
        {
          if (num_fetching == max_fetching) break;
          if (inst.fetching || inst.fetched) continue;
          var ts = new ThreadStart(inst.run);
          var thread = new Thread(ts);
          thread.Start();
          num_fetching++;
          break;
        }
        num_fetched = 0;
        num_fetching = 0;
        foreach (var inst in insts)
        {
          if (inst.fetching) num_fetching++;
          if (inst.fetched) num_fetched++;
        }
        Thread.Sleep(150);
      }
      Console.WriteLine("Done");
      foreach (var inst in insts)
      {
        Console.WriteLine(inst.value);
      }
    }
  }

Leave a Reply