c# - 在压缩一个巨大的文件夹时,如何为其他应用程序提供一些磁盘时间? C#

标签 c# multithreading zip

我有一个巨大的文件夹,每天晚上都必须通过应用程序进行压缩。但是,它会在该时间段内消耗主要磁盘性能,并且可持续 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 这样的库

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/

相关文章:

C# 展开 Flat List<T> 到 Dictionary<T,ICollection<int>>

multithreading - 使用 `threadDelay` 时系统调用量过多

iphone - NSOperationQueueDefaultMaxConcurrentOperationCount 的线程数

java - Websphere ScheduledExecutorService 线程

ios - 如何在 iOS Swift 中从本地目录加载index.html 文件?

ruby - 在 Ruby 中创建 tgz 文件

C# 4.0 - 如何处理可选的字符串参数

c# - 使用 nHibernate 和 Json.Net 公开部分对象

c# - 如何使用 C# 以编程方式将 html 字符串直接传递给 Web 浏览器?

java - 使用javac编译时的问题