SamIAm
SamIAm

Reputation: 2491

Which methods should be used for threads and copying files?

I have a method that will copy a file from one directory to another. The files will be huge and I want to use threads to ensure the console doesn't lock up.

What is the best method of using threads when copying files? I have read up and it seems there are three methods of using threads: Threadpool, Threads, Asynchronous methods.

Are there clear benefits of using one over the other?

Upvotes: 3

Views: 2978

Answers (1)

Johnathon Sullinger
Johnathon Sullinger

Reputation: 7414

If you want to run it on a background thread, the recommended approach now (unless you need a specific reason not to) is to use Tasks from the TPL

You can perform your file copy using the following code, which will run on a background thread.

Task.Run(() => System.IO.File.Copy(someFile, newFile));

If you need to perform additional code when the task is completed, you can do so with a continuation.

Task.Run(() => System.IO.File.Copy(someFile, newFile)).ContinueWith(() => 
    {
        // Some more stuff to do once copy is completed.
    });

Edit

An alternative, if you are performing a copy on a large number of files, is to run them in parallel. The TPL library handles the threadpool properly and ensures everything runs as it should.

Task.Run(() = >
{
    collectionOfFiles.AsParallel.ForAll(file => System.IO.File.Copy(file, newFile));
}

Or something more fancy if needed.

Task.Run(() =>
{
    collectionOfFiles.AsParallel().ForAll(file => 
    {
        string newFile = string.Format(@"C:\{0}", file);
        System.IO.File.Copy(file, newFile);
        // Do more
     });
});

That will copy all of the files, in parallel, on a worker thread.

Upvotes: 3

Related Questions