0

Lets say I have a program, this program has an int variable named 'number', and I want to make a background loop that will add 1 to 'number', while im doing some calculations in the main program. I know I need to use Threading, I tried but it does'nt work. Can you help me out with it? Thank you very much!

Shaxib
  • 43
  • 2
  • 7
  • Im trying to check if a key has been pushed, if so I want to insert it into a ConsoleKey variable. – Shaxib Nov 14 '15 at 21:02
  • Please post the code that you have, so that we can use that to explain where you went wrong and how it can be improved. Otherwise its just "please program that for me" – Domysee Nov 14 '15 at 21:03
  • You say you tried but `it doesn't work`. Let us see what you have tried, and maybe we can find what needs to be fixed in your code. – Luc Morin Nov 14 '15 at 21:06
  • I checked it and my bug has nothing to do with the threading, it's something else I cant find. Thank you anyways guys:) – Shaxib Nov 14 '15 at 21:13

1 Answers1

4

This program will spawn a separate thread. You can easily replace my two loops with your own code.

using System;
using System.Threading;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            var ts = new ThreadStart(BackgroundMethod);
            var backgroundThread = new Thread(ts);
            backgroundThread.Start();

            // Main calculations here.
            int j = 10000;
            while (j > 0)
            {
                Console.WriteLine(j--);
            }
            // End main calculations.
        }

        private static void BackgroundMethod()
        {
            // Background calculations here.
            int i = 0;
            while (i < 100000)
            {
                Console.WriteLine(i++);
            }
            // End background calculations.
        }
    }
}
LVBen
  • 2,041
  • 13
  • 27
  • Thank you, i did something like that and it worked. Now i have another bug i should fix, thank you buddy :) – Shaxib Nov 14 '15 at 21:16