在我的以下代码中, Timer_Elapsed 事件未命中。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.IO;
using System.Reflection;
using System.Diagnostics;
namespace Logger
{
internal class Country
{
public string CountryName { get; set; }
public string CountryCode { get; set; }
}
internal class CountryLogger
{
List<Country> countries = new List<Country>()
{
new Country{CountryName = "India", CountryCode="IND"},
new Country{CountryName = "United States of America", CountryCode="USA"},
new Country{CountryName = "United Kingdom", CountryCode="UK"},
new Country{CountryName = "Australia", CountryCode="AUS"}
};
public void WriteToLog()
{
string fileName = @"C:\ParallelLog.txt";
using (StreamWriter writer = new StreamWriter(fileName, true))
{
foreach (Country Country in countries.AsParallel().AsOrdered())
{
writer.WriteLine("{0} - {1}", Country.CountryName, Country.Count ryCode);
writer.WriteLine();
}
}
}
}
internal class Program
{
static void Main(string[] args)
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Enabled = true;
timer.Interval = 3 * 60 * 1000;
timer.Elapsed += new System.Timers.ElapsedEventHandler(Timer_Elapsed);
}
static void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
//for (int i = 0; i < 10; i++)
//{
Task task = Task.Factory.StartNew(() =>
{
CountryLogger countriesLogger = new CountryLogger();
countriesLogger.WriteToLog();
});
//}
}
}
}
Task task = Task.Factory.StartNew(() => object也没有通过 for 循环循环(因为它不起作用而被评论)。
有人可以建议编写此代码的更好方法吗?