Semaphores C# Two threads

Lenny

The idea of my code is to WRITE into file(.txt) a letter then READ that file and if the letter that was read is consonant then it outputs it. If not, does nothing.

I am using Semaphores to do this. Created two threads. It WRITES and READS from file. However, cannot get this condition running. For some reason when reading from the file it shows conversion error. and the "letter" variable is equal to '\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();
    }
}

}

Access Denied

Read all lines returns string[]. In order to convert it to char you need to get first line and first char from the first line:

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related