如何复制多个线程的文件?

时间:2014-05-12 13:25:23

标签: c# multithreading

我想以15分钟的间隔复制文件。我不想使用任务计划程序。

基本上,我执行所有三个线程并让线程自己处理。方法RunWhenItsTime()基本上监视当前时间并检查RunTime是否等于CurrentTime。如果是,则RunWhenItsTime()调用开始复制文件的CopyFiles()

以下代码是否有效?出于某种原因,它会卡在某处,但我不知道它在哪里。

这是我的代码:

Class myClass0 = new Class();
Thread0 = new Thread(() => myClass0.RunWhenItsTime(FirstQtrRun, 0, cts0.Token));
Thread0.Start();

Class myClass1 = new Class();
Thread1 = new Thread(() => myClass1.RunWhenItsTime(SecondQtrRun, 1, cts1.Token));
Thread1.Start();

Class myClass2 = new Class();
Thread2 = new Thread(() => myClass2.RunWhenItsTime(ThirdQtrRun, 2, cts2.Token));
Thread2.Start();

Class myClass3 = new Class();
Thread3 = new Thread(() => myClass3.RunWhenItsTime(FourthQtrRun, 3, cts2.Token));
Thread3.Start();

public void RunWhenItsTime(DateTime RunTime, int Period, Object obj)
{
    Console.WriteLine("Task Has been set to run at: " + RunTime.ToString(), " for Period: " + Period.ToString());
    DateTime CurrentTime = DateTime.Now;
    for (; ; )
    { //Check that CurrentTime is equal to RunTime.
        Console.WriteLine("Runtime: " + RunTime.ToString() + "   |   " + "Current Time: " + CurrentTime.ToString() 
            + "PERIOD: " + Period.ToString());
        if ((CurrentTime.Year == RunTime.Year) && (CurrentTime.Month == RunTime.Month) &&
            (CurrentTime.Day == RunTime.Day) && (CurrentTime.Hour == RunTime.Hour) &&
            (CurrentTime.Minute == RunTime.Minute))
        {
            CopyFiles(RunTime, Period, obj);
            break;
        }
        CurrentTime = DateTime.Now;
    }
}

2 个答案:

答案 0 :(得分:2)

首先执行一个无限循环而不让线程在没有任何事情要做的时候休眠(你这样做3次),这会杀死你的CPU利用率:

for (; ; )
{ //Check that CurrentTime is equal to RunTime.
    Console.WriteLine("Runtime: " + RunTime.ToString() + "   |   " + "Current Time: " + CurrentTime.ToString() 
        + "PERIOD: " + Period.ToString());
    if ((CurrentTime.Year == RunTime.Year) && (CurrentTime.Month == RunTime.Month) &&
        (CurrentTime.Day == RunTime.Day) && (CurrentTime.Hour == RunTime.Hour) &&
        (CurrentTime.Minute == RunTime.Minute))
    {
        CopyFiles(RunTime, Period, obj);
        break;
    }
    CurrentTime = DateTime.Now;
    System.Threading.Thread.Current.Sleep(1000);  // sleep 1 second
}

其次,你真的只应该有一个循环,这个循环应该确定你的3个条件中的任何一个条件的时间到CopyFiles并执行(如果你想要的话,线程/任务)那。一旦满足所有3个条件,退出定时循环。

答案 1 :(得分:1)

您可能不应该使用无限循环来直接测试当前时间以及文件复制的时间。更好的解决方案是使用C#' Timer类。以下链接有一个很好的例子。

Using C# Timer class

使用这种方法你仍然可以使用你的线程但不会占用你所有的CPU,并且可能会更加可靠。