问题描述:

I am trying to write a small threaded application and wanted to know how I could implement the below IEnum as thread/threaded? Absolute beginner to threading, not even sure the below method can be threaded. Would appreciate a little walk through.

 static void Main(string[] args)

{

IEnumerable<string> e = Enumerable.Range(1, 100).Select(

n =>

(n % 15 == 0) ? "Fizzbuzz" :

(n % 3 == 0) ? "Fizz" :

(n % 5 == 0) ? "buzz" :

n.ToString())

.ToList();

WriteFile(e);

}

private static ReaderWriterLockSlim _readWriteLock = new ReaderWriterLockSlim();

private static void WriteFile(IEnumerable<string> text)

{

_readWriteLock.EnterWriteLock();

string path = @"C:\Users\Desktop\Test.txt";

try

{

using (StreamWriter stream = File.AppendText(path))

{

foreach (var item in text)

{

stream.WriteLine(item);

}

stream.Close();

}

}

catch (Exception e)

{

throw (e);

}

finally

{

// Release lock

_readWriteLock.ExitWriteLock();

}

}

网友答案:

Does this work for you?

static void Main(string[] args)
{
    IEnumerable<string> e =
        Enumerable
            .Range(1, 100)
            .AsParallel()
            .Select(
                n =>   
                    (n % 15 == 0) ? "Fizzbuzz" :
                    (n % 3 == 0) ? "Fizz" :
                    (n % 5 == 0) ? "buzz" :
                    n.ToString())
            .ToList();
    WriteFile(e);
}

private static ReaderWriterLockSlim _readWriteLock = new ReaderWriterLockSlim();
private static void WriteFile(IEnumerable<string> text)
{
    try
    {
        _readWriteLock.EnterWriteLock();
        File.AppendAllLines(@"C:\Users\Desktop\Test.txt", text);
    }
    finally
    {
        _readWriteLock.ExitWriteLock();
    }
}

Note the .AsParallel() call.

But, if you do do it this way then there is no need for the locks.

相关阅读:
Top