2013-10-10 71 views
1

我用C#编写的代码: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(); 
     } 
    } 
} 

现在,我得到这个错误:

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

它说,有关“input.Abort(); “线。

我可以以某种方式从另一个方法终止此线程(而不是从它创建的地方)?

我不想让它们成为静态的,所以请不要这么说。

+2

Thread.Abort的()是真的真的[衰](http://stackoverflow.com/questions/710070/timeout-pattern-how-bad-is-thread-abort - 当然)... – Chris

+0

'控制台'块。 –

回答

3

您需要使用类字段而不是局部变量。

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

无关的问题本身,你不应该使用多线程强行中止一个从控制台读取。相反,您应该使用Sleep和Console.KeyAvailable属性的组合。

+0

非常感谢。 我想了解更多关于“this”和class fields的主题。我在哪里可以了解更多关于班级领域以及如何使用它们? – BlueRay101

+0

而且,如果在方法中声明了一个线程,它是一个被认为是局部变量的线程? – BlueRay101

+0

任何你在form中定义的方法'SomeType variable = something();'被认为是一个局部变量。 –

1

应该

public void actual() 
    { 
     Thread input = new Thread(input_m); 
     if(input.Join(TimeSpan.FromSeconds(10))) 
        //input complete 
     else 
        //timeout 
    } 
+0

谢谢,但我更喜欢Knagis所建议的方式,因为它使我能够更全面地控制线程。 – BlueRay101