R
R
Roman Koff2016-10-03 15:33:00
C++ / C#
Roman Koff, 2016-10-03 15:33:00

How to implement asynchronous file creation?

The task is very simple, the graphic files in the folder are sorted and for each file its thumbnails are created for several sizes. The task runs for a long time. How can it be rewritten with an asynchronous approach, and does it make sense?

public void MakeCopys(string path)
{
  var di = new DirectoryInfo(path);
  foreach (var file in di.GetFiles("*.jpg"))
  {
    MakeThumbnails(file);
  }
}

public void MakeThumbnails(FileInfo file)
{
  MakeThumbnail(file, 75, file.FullName + ".lg.jpg");
  MakeThumbnail(file, 50, file.FullName + ".md.jpg");
  MakeThumbnail(file, 25, file.FullName + ".sm.jpg");
}

public void MakeThumbnail(FileInfo file, int size, string name)
{
  // код генерации уменьшенной копии
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Ananiev, 2016-10-03
@SaNNy32

Use Parallel.For

V
Vladimir S, 2016-10-03
@hePPer

can it be like this

public void MakeCopys(string path)
{
var di = new DirectoryInfo(path);
Parallel.ForEach(di.GetFiles("*.jpg"),  new ParallelOptions {MaxDegreeOfParallelism = 10}, (file) =>
{
MakeThumbnails(file);
});
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question