Task.Factory.StartNew()没有触发ElapsedEventHandler事件

时间:2013-07-05 06:28:05

标签: c# task-parallel-library

在我的以下代码中,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.Factory.StartNew(()=&gt; 对象没有循环遍历for循环(已注释,因为它不起作用)。

有人可以建议更好的方法来编写此代码吗?!

1 个答案:

答案 0 :(得分:1)

第一个程序线程在让计时器运行时应该做什么?

在这里,我只是在等待用户点击返回:

static void Main(string[] args)
    {
        System.Timers.Timer timer = new System.Timers.Timer();
        timer.Elapsed += new System.Timers.ElapsedEventHandler(Timer_Elapsed);
        timer.Interval = 3 * 60 * 1000;
        timer.Enabled = true;
        Console.WriteLine("Press return to exit");
        Console.ReadLine();
        GC.KeepAlive(timer); //Can't decide if this is needed or not
    }

重要的是,如果您return Main(或者只是点击最后}),您的程序就会退出。我不记得定时器是否在垃圾收集方面保持活力,所以为了以防万一,我添加了GC.KeepAlive


我还改变了计时器上的分配顺序 - 这样它就不会启用,直到我知道处理程序被连接并且间隔设置正确。