devha
devha

Reputation: 3367

.net 4.0 asynchronous file copy

I have small .net 4.0 application which basically compares file dates, if the files are changed copyes these from location a to location b. While this copy job is done, it displays little UI with progress bar etc.

How to do this file last write time comparision and file copy asynchronously? As im starting to do this right after the app is started, the app ui is loading very slowly and ui is not updated correcty (as my app is waiting file copy etc).

EDIT: ...and I want to update the UI from long running file task, BackgroundWorker has option for this but what about other options?

Upvotes: 1

Views: 1952

Answers (3)

Adrian Trifan
Adrian Trifan

Reputation: 250

If you only want to notify UI after the operation completes, you can use this (on .Net 4.0):

Task.Factory.StartNew(() =>
            {
                //Copy file here
            }).ContinueWith((prevTask) =>
                {
                    if (prevTask.Exception != null)
                    {
                        // log/display exception here
                        return;
                    }
                    //display success result here
                }, TaskScheduler.FromCurrentSynchronizationContext());

If you want to copy multiple files an notify UI during that process, you can use this:

        var currentSyncContext = SynchronizationContext.Current;
        Task.Factory.StartNew(() =>
            {
                //do some work
                currentSyncContext.Send(new SendOrPostCallback((arg) =>
                {
                    //your UI code here
                }), "your current status");
                //do some work
            });

Upvotes: 1

Bram Van Strydonck
Bram Van Strydonck

Reputation: 934

You can achieve this by creating a Task (e.g. do it in your load method)

Task.Run(() => DoHeavyStuf());

The method where you can do heavy stuf async (e.g. I/O)

private void DoHeavyStuf()
{
   //Heavy work (simulated by thread.sleep)
   System.Threading.Thread.Sleep(5000);
   MessageBox.Show("Heavy stuf completed");
}

For .NET 4.0 you could use (credits: Rotem)

new Task(DoHeavyStuf).Start();

Upvotes: 1

Rik
Rik

Reputation: 29243

You can use a BackGroundWorker for this type of thing:

BackGroundWorker worker = new BackGroundWorker();
worker.DoWork += myWorkDelegate; // method, delegate or lambda that does the heavy work
worker.RunWorkerCompleted += myCompletedDelegate; //method delegate or lambda to execute when DoWork has finished

worker.RunWorkerAsync();

Upvotes: 0

Related Questions