永发信息网

c#多线程get后写入文件。 1.比如现在要get 500个网页取得内容,我是直接循环500次然后

答案:2  悬赏:60  手机版
解决时间 2021-01-29 08:43
  • 提问者网友:锁深秋
  • 2021-01-28 16:32
c#多线程get后写入文件。
1.比如现在要get 500个网页取得内容,我是直接循环500次然后task去get,请问有没有更好的方法?

2.每次get完后把结果写到文件里面,以文件流的形式,必须按顺序比如第一次get后的数据写了才能写第二次的。

求诸位解答!
最佳答案
  • 五星知识达人网友:蓝房子
  • 2021-01-28 17:53
1. 如果你的程序的主要任务就是循环get,并写文件,其实只需要开两个线程就可以了,一个负责循环get,因为多个线程并不能显增加get的速度,获取到了内存,另一个线程负责写文件
2. 如果你写的是一个文件,那就要考虑多线程的访问冲突问题,所以建议每次get创建并写不同的文件,可以按日期时间来命名,等全部get完一次性合并所有文件就很快了
全部回答
  • 1楼网友:狂恋
  • 2021-01-28 19:29
用一个monitor锁定就ok了,下面是完整代码,你可以直接复制过去运行的class program    {        private event eventhandler onnumberclear;        public list<thread> threadcollection = new list<thread>();        public int count = 0;        private void run()        {            while (true)            {                monitor.enter(this);//锁定,保持同步                console.writeline("线程{0}正在运行{1}", thread.currentthread.name, count);                if (count == 50)                {                    onnumberclear(this, new eventargs());//引发完成事件                }                count += 1;                monitor.exit(this);//取消锁定                thread.sleep(5);            }         }        public program()        {            for (int i = 0; i < 10; i++)            {                thread mythread = new thread(run);                mythread.name = string.format("{0}", i);                threadcollection.add(mythread);            }            onnumberclear += new eventhandler(program_onnumberclear);         }         void program_onnumberclear(object sender, eventargs e)        {            console.writeline("执行完了,停止了所有线程的执行。");            foreach (thread thread in threadcollection)            {                thread.abort();            }        }        public void action()        {            foreach (thread thread in threadcollection)            {                thread.start();            }        }        static void main(string[] args)        {            program program = new program();            program.action();        }    }
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯