0

在我的以下代码中, 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 循环循环(因为它不起作用而被评论)。

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

4

1 回答 1

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
    }

重要的,如果您returnMain(或刚刚达到 final }),您的程序将退出。我不记得计时器是否在垃圾收集方面保持活跃,所以我添加了一个GC.KeepAlive以防万一。


我还切换了计时器上的分配顺序 - 这样它就不会启用,直到我知道处理程序已附加并且间隔设置正确。

于 2013-07-05T06:58:19.943 回答