2015-11-17 57 views
0

我的代码的想法是写入文件(.txt)一个字母然后读取该文件,如果读取的字母是辅音,然后输出它。如果没有,什么也不做。信号量C#两个线程

我正在使用信号量来做到这一点。创建了两个线程。它从文件中写入和读取。但是,无法运行此条件。由于某些原因,从文件中读取时会显示转换错误。而“字母”变量等于'\ 0'。

Here is the error

Here is the letter variable, it has hold the value that is in .txt

namespace Sema 
{ 
class Program 
{ 
    private static Semaphore sPhore = new Semaphore(2, 2); 
    public static string path = "message.txt"; 

    private static void write(object input) 
    { 


     Console.WriteLine("\nEnter the consonant: "); 
     sPhore.WaitOne(); 
     input = Console.ReadLine(); 
     TextWriter tw = File.CreateText(path); 
     tw.WriteLine(input); 
     tw.Close(); 
     sPhore.Release(); 
    } 
    private static void read(object input) 
    { 
     sPhore.WaitOne(); 
     char letter = Convert.ToChar(File.ReadAllLines(path)); 
     //char letterChar = Convert.ToChar(letter); 
     if (letter.Equals('q') || letter.Equals('w') || letter.Equals('r') || letter.Equals('t') || letter.Equals('p') || letter.Equals('s') 
     || letter.Equals('d') || letter.Equals('f') || letter.Equals('g') || letter.Equals('h') || letter.Equals('j') || letter.Equals('k') 
     || letter.Equals('l') || letter.Equals('z') || letter.Equals('x') || letter.Equals('c') || letter.Equals('v') || letter.Equals('b') 
     || letter.Equals('n') || letter.Equals('m')) 
     { 
      Console.WriteLine("\nYou wrote this consonant:" + letter); 
     } 

      //TextReader tr = File.OpenText("message.txt"); 
     //Console.Write("\nYou wrote this char:" + tr.ReadAsync()); 
     //tr.Close(); 
     sPhore.Release(); 
    } 
    //private static void read(object path) 
    //{ 

    //} 
    static void Main(string[] args) 
    { 

     for (int i = 0; i < 4; i++) 
     { 
      Thread ss = new Thread(new ParameterizedThreadStart(write)); 
      Thread sss = new Thread(new ParameterizedThreadStart(read)); 
      ss.Start(i); 
      ss.Join(); 
      sss.Start(i); 
      sss.Join(); 
     } 
     Console.ReadLine(); 
    } 
} 

}

+1

阅读所有行返回一个数组,即使该文件只包含一行。 –

回答

1

阅读全部线返回字符串[]。为了将其转换为char你需要从第一行第一行第一个字符:

char letter = File.ReadAllLines(path)[0][0]; 
+0

哦,我的...谢谢!你是对的! – Lenny