如何写一个IEnum线程
How to write a IEnum thread
我正在尝试编写一个小型线程应用程序,想知道如何将下面的 IEnum 实现为 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();
}
}
这对你有用吗?
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()
调用。
但是,如果你这样做,那么就不需要锁了。
我正在尝试编写一个小型线程应用程序,想知道如何将下面的 IEnum 实现为 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();
}
}
这对你有用吗?
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()
调用。
但是,如果你这样做,那么就不需要锁了。