如何编写IEnum线程

时间:2015-05-05 02:37:00

标签: c# multithreading thread-safety locking

我正在尝试编写一个小型线程应用程序,并想知道如何将{IE1um}实现为thread/threaded?线程的绝对初学者,甚至不确定以下方法是否可以线程化。希望稍微走一走。

    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();
        }
    }

1 个答案:

答案 0 :(得分:2)

这对你有用吗?

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();
    }
}

请注意.AsParallel()来电。

但是,如果你这样做,那么就不需要锁了。