1

I've written this code in C#:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Program re = new Program();
            re.actual();
        }
        public void actual()
        {
            Thread input = new Thread(input_m);
            Thread timing = new Thread(timing_m);
            input.Start();
            timing.Start();
        }
        public void input_m()
        {
            Console.WriteLine("Choose a number from 1-10 (You have 10 seconds): ");
            Console.ReadKey();
        }
        public void timing_m()
        {
            System.Threading.Thread.Sleep(10000);
            input.Abort();
            Console.Clear();
            Console.WriteLine("Time's up!");
            Console.ReadKey();
        }
    }
}

Now, I get this error:

Error   1   The name 'input' does not exist in the current context

It says that about the "input.Abort();" line.

Can I somehow terminate this thread from another methods (not from where it was created)?

I don't want to make them static by the way, so please don't suggest that.

BlueRay101
  • 1,447
  • 2
  • 18
  • 29
  • 2
    Thread.Abort() is really really [bad](http://stackoverflow.com/questions/710070/timeout-pattern-how-bad-is-thread-abort-really)... – Chris Oct 10 '13 at 15:42

2 Answers2

3

You need to use a class field instead of a local variable.

class Program
{
    private Thread input;
    public void actual()
    {
        this.input = new Thread(input_m);
        //...
    }
 }

Unrelated to the problem itself, you should not use multiple threads and forcibly abort the one that reads from the console. Instead you should use a combination of Sleep and Console.KeyAvailable property.

Knaģis
  • 20,827
  • 7
  • 66
  • 80
  • Thank you very much. I'm interested in learning more regarding the "this" and class fields subject. Where can I learn more about class fields and how to use them? – BlueRay101 Oct 10 '13 at 15:45
  • And also, is a thread considered a local variable if declared in a method? – BlueRay101 Oct 10 '13 at 15:45
  • anything that you define in a method in form `SomeType variable = something();` is considered a local variable. – Knaģis Oct 10 '13 at 15:51
1

It should be

    public void actual()
    {
        Thread input = new Thread(input_m);
        if(input.Join(TimeSpan.FromSeconds(10)))
                    //input complete
        else
                  //timeout
    }
Anirudha
  • 32,393
  • 7
  • 68
  • 89
  • Thank you, but I prefer the way that Knagis suggested, since it gives me more general control over the thread. – BlueRay101 Oct 10 '13 at 16:06