我的c#程序流程出现问题

时间:2017-03-15 20:53:29

标签: c# debugging timer event-handling

我正在编写一个包含多个事件处理程序的程序,这对我来说是一个新领域。一个事件处理程序监视文件夹,当文件移入其中时,它会打开文件,从文件中获取一条信息,将该数据存储在对象列表中,然后将文件移动到另一个文件夹。第二个事件处理程序基于计时器,其间隔设置为10秒。当计时器过去时,它循环遍历列表,我已经加载并检查项目加载到列表的时间戳是否超过1分钟,如果是,那么它只显示一条消息给安慰。我有两个主要问题:第一)每分钟显示一次应该显示给控制台的消息比它应该更频繁地显示(大约每15秒一次而不是每分钟一次)和2)当我尝试调试程序时然后它会到达计时器事件处理程序,它会跳到没有跟随任何逻辑路径到我的地方(我可能错了)。拜托,有人可以帮帮我吗?任何帮助将非常感激。

代码:

public class fileObject
    {
        public string strPONumber { get; set; }
        public DateTime dtArrival { get; set; }
    }
    private static System.Timers.Timer aTimer;
    public static void Main()
    {
        Run();
    }

    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    public static void Run()
    {
        Console.WriteLine("redefined");
        List<fileObject> lstPONums = new List<fileObject>();

        // Create a new FileSystemWatcher and set its properties.
        FileSystemWatcher watcher = new FileSystemWatcher();
        watcher.Path = @"C:\Users\z088476\Desktop\FolderA\";



        // Only watch text files.
        watcher.Filter = "*";

        // Add event handlers.

        Console.WriteLine("before event");

        watcher.Created += new FileSystemEventHandler((sender, e) => OnChanged(sender, e, lstPONums));


        aTimer = new System.Timers.Timer();

        aTimer.Elapsed += new ElapsedEventHandler((sender, e) => OnTimedEvent(sender, e, lstPONums));
        aTimer.Interval=10000;
        aTimer.Enabled = true;


        Console.WriteLine("Press \'q\' to quit the sample.");
        while (Console.Read() != 'q') ;
    }

    // Define the event handlers.
    private static void OnChanged(object source, FileSystemEventArgs e, List<fileObject> lstPONumbers)
    {
        fileObject fObj = new fileObject();
        string strLine = "";
        using (StreamReader sr = new StreamReader(e.FullPath))
        {
            strLine = sr.ReadLine();
        }
        string strDelim = strLine.Substring(3,1);
        List<string> lstSplit = new List<string>();
        lstSplit = strLine.Split(Convert.ToChar(strDelim)).ToList();
        fObj.strPONumber = lstSplit[30];
        fObj.dtArrival = DateTime.Now;
        lstPONumbers.Add(fObj);
        File.Move(e.FullPath, @"C:\Users\z088476\Desktop\FolderC\" + e.Name);
    }


    private static void OnTimedEvent(object source, ElapsedEventArgs e, List<fileObject> lstPONumbers)
    {

        if (lstPONumbers.Count != 0)
        {
            foreach (fileObject fo in lstPONumbers)
            {
                DateTime dtnow = DateTime.Now;
                TimeSpan duration = DateTime.Now - fo.dtArrival;
                if (duration.TotalMinutes > 1)
                {
                    Console.WriteLine("IT IS MORE THAN 1 MIN!!!!");
                }
            }
        }
    }

0 个答案:

没有答案