使用2个线程用C#写入2个文本文件

时间:2014-11-15 20:05:18

标签: c# multithreading

我想写一个C#控制台应用程序
使用两个线程写入两个文本文件。 这两个文件包含从1到2000的所有数字,但在2个文件中没有重复两次 作为第一个文件(123 ......),第二个文件(456 .....)

谢谢

1 个答案:

答案 0 :(得分:0)

您需要将数据分成块。这有几种算法,但我会用“奇数和偶数”进行演示。

这对你有帮助吗?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {


            //odd
            Thread _th1 = new Thread(new ThreadStart(delegate
            {
                StreamWriter sw = File.AppendText("thread1.txt");
                for (int i = 0; i <= 2000; i=i+2)
                {
                    Console.WriteLine("th1:" + i.ToString());
                    sw.Write(i.ToString()+";");    
                }
                sw.Close();
            }));

            //even
            Thread _th2 = new Thread(new ThreadStart(delegate
            {
                StreamWriter sw = File.AppendText("thread2.txt");
                for (int i = 1; i <= 2000; i = i + 2)
                {
                    Console.WriteLine("th2:" + i.ToString());
                    sw.Write(i.ToString()+";");
                }
                sw.Close();
            }));

            _th1.Start();
            _th2.Start();

            Console.Read();
        }
    }
}
相关问题