Задача отсюда Реализация программы с потоками
По шагово отладчиком прошёлся и id,m_threadresult,localstat у меня то 1 и 0 соответственно. А где откорректировать чтобы не вылетало.
Ведь когда получил список файлов при помощи парсинга,я должен каждый записать в итоговый отдельный файл. Но не выходит.
Скрип с местом где исключение.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Text;
using System.IO;
using System.Diagnostics.Eventing.Reader;
using System.Threading.Tasks;
namespace Лабораторная_2
{
class countFiles
{
string[] filelist = Directory.GetFiles(@"D:\logfiles", "*.txt");
public string user
{ get; set; }
public string adres
{ get; set; }
public int trafik
{ get; set; }
public string data
{ get; set; }
public countFiles(string userr="", string adress="", int traffic=0)
{
user = userr;
adres = adress;
trafik = traffic;
}
public void parsingfiles(string lline)
{
List<countFiles> list = new List<countFiles>(); //здесь будет результат
for (int i = 1; i < filelist.Length; i++)
{
if (filelist[i] == "")
continue;
string[] lineParts = filelist[i].Split(' ');
list.Add(new countFiles(lineParts[0], lineParts[1], int.Parse(lineParts[2])));
}
}
public void ReadFile(string filename)
{
using (StreamReader sr = new StreamReader(filename))
{
string line;
while ((line = sr.ReadLine()) != null)
{
parsingfiles(line);
}
}
}
}
class StatLog
{
public Dictionary<String, UInt64> userstat;
public Dictionary<String, UInt64> adrestat;
public Dictionary<int, UInt64> trafikstat;
public StatLog()//конструктор
{
userstat = new Dictionary<String, UInt64>();
adrestat = new Dictionary<String, UInt64>();
trafikstat = new Dictionary<int, UInt64>();
}
public StatLog createStat(StatLog info)//
{
UInt64 value;
foreach (var item in info.userstat)
{
userstat[item.Key] = (userstat.TryGetValue(item.Key, out value) ? value : 0) + item.Value;
}
foreach (var item in info.adrestat)
{
adrestat[item.Key.Trim()] = (adrestat.TryGetValue(item.Key.Trim(), out value) ? value : 0) + item.Value;
}
foreach (var item in info.trafikstat)
{
trafikstat[item.Key] = (trafikstat.TryGetValue(item.Key, out value) ? value : 0) + item.Value;
}
return this;
}
}
class injectfile
{
static System.Collections.Generic.List<StatLog> m_threadResult;//результат выполнения потока
static Queue<String> m_workFiles = new Queue<String>();//очередь файлов с каталога
static bool m_iscomplete = false;//флаг завершения ввода
static readonly object m_locker = new object(); //мютекс для работы с файлами выводимых в очередь
public void injected(String filelist)//выгрузка файлов в очередь для обработки
{
if (!Directory.Exists(filelist))
{
return;
}
lock (m_locker)
{
foreach (var x in Directory.EnumerateFiles(filelist))
{
m_workFiles.Enqueue(x);
}
}
m_iscomplete = true;//установить флаг завершения
}
public static StatLog processFile(String file)//обработка файла
{
if (!File.Exists(file))///Проверка на наличие файла в каталоге
{
return new StatLog();
}
StreamReader sr = System.IO.File.OpenText(file);
String line;
StatLog sc = new StatLog();//
countFiles cnt = new countFiles();
while ((line = sr.ReadLine()) != null)
{
cnt.parsingfiles(line);
}
return sc;
}
static public void threadFunc(int id)
{
String value;
StatLog localStat = m_threadResult[id];
StatLog sc = new StatLog();
while (true)
{
lock (m_locker)
{
if (m_workFiles.Count < 1)
{
if (m_iscomplete)
{
break;
}
continue;
}
value = m_workFiles.Dequeue();//получение первого файла из очереди с удалением его из очереди
}
var filestat = processFile(value);//обработать файл
localStat.createStat(filestat);//объеденить статистику
}
}
}
class Program
{
static void Main(string[] args)
{
int threadCount = 7;//задаём количество потоков
string[] filelist = Directory.GetFiles(@"D:\logfiles", "*.txt");
System.Collections.Generic.List<StatLog> m_threadResult;//результат выполнения потока
m_threadResult = new System.Collections.Generic.List<StatLog>(threadCount);
//и массив потоков
System.Threading.Thread[] threads = new System.Threading.Thread[threadCount];
for (int i = 0; i < threadCount; ++i){
int id = i;
m_threadResult.Add(new StatLog());
threads[i] = new System.Threading.Thread(() => injectfile.threadFunc(id));
threads[i].Start();
}
var statResult = m_threadResult[0];
for (int i = 1; i < m_threadResult.Count; ++i){
statResult.createStat(m_threadResult[i]);
}
Console.WriteLine("Создание файлов статистик");
StreamWriter sw = new StreamWriter(@"D:\userstat.txt");
//Пишем в файл
foreach (var item in statResult.userstat){
sw.WriteLine("{0} {1}", item.Key, item.Value);
Console.WriteLine("{0} {1}", item.Key, item.Value);
}
sw.Close();
StreamWriter sw1 = new StreamWriter(@"C:\adrestat.txt");
foreach (var item in statResult.adrestat){
sw1.WriteLine("{0} {1}", item.Key, item.Value);
Console.WriteLine("{0} {1}", item.Key, item.Value);
}
sw1.Close();
StreamWriter sw2 = new StreamWriter(@"D:\trafikstat.txt");
foreach (var item in statResult.trafikstat)
{
sw2.WriteLine("{0} {1}", item.Key, item.Value);
Console.WriteLine("{0} {1}", item.Key, item.Value);
}
sw2.Close();
Console.WriteLine("Файлы созданы");
Console.ReadKey();
}
}
}