我有一个巨大的文件夹,每天晚上都必须通过应用程序进行压缩。但是,它会在该时间段内消耗主要磁盘性能,并且可持续 10 分钟。我想让它成为一个线程,暂停2秒,再取消暂停2秒,就像一个循环一样。我不介意它持续更长时间,因为我希望它仍然为其他应用程序提供一些磁盘时间
开始 > 暂停 2 秒 > 恢复 2 秒 > 暂停 2 秒 > 恢复 2 秒 >......完成
static void Main(string[] args)
{
zipFolder(@"c:\example\start", @"c:\example\result.zip");
}
static void zipFolder(string startPath, string zipPath)
{
ZipFile.CreateFromDirectory(startPath, zipPath);
}
最佳答案
我建议使用像 DotNetZip
这样的库
然后您可以创建一个简单的包装器,如下所示。
public class ScheduleZipper
{
private int _interval;
private DateTime _lastZip;
private string _source;
private string _dest;
public ScheduleZipper(string source, string dest, int interval)
{
_interval = interval;
_lastZip = DateTime.Now.AddMilliseconds(_interval);
}
private void ZipFilesInFolder(string path, ZipFile zip)
{
foreach (var file in Directory.GetFiles(path))
{
if (DateTime.Now >= _lastZip.AddMilliseconds(_interval))
{
System.Threading.Thread.Sleep(_interval);
_lastZip = DateTime.Now;
}
zip.AddFile(file);
}
foreach (var dir in Directory.GetDirectories(path))
{
ZipFilesInFolder(path, zip);
}
}
public void Zip()
{
using (var zip = new ZipFile(_dest))
{
ZipFilesInFolder(_source, zip);
}
}
}
只需做这样的事情
var schedule = new ScheduleZipper(@"c:\example\start", @"c:\example\result.zip", 2000);
schedule.Zip();
如果您的程序正在执行其他操作,那么您可以将其包装到线程中。
注意:您可能需要修改代码来创建您想要的 zip 存档,其中包含文件夹等。
关于c# - 在压缩一个巨大的文件夹时,如何为其他应用程序提供一些磁盘时间? C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32139458/