A Coder
A Coder

Reputation: 3046

Task.Delay inside thread C#

I'm working in a WPF application where i'm making a save process inside a thread. After the save process i'm initiating the load process between that i need a delay so i used the Task.Delay method.

During the save/load a progress bar is shown in the application untill it completes. Now when i use the Task.Delay method for 2 seconds no progress bar is shown in the application.

Now the issue is the delay(2 seconds). When there is a delay the user starts using the application and suddenly the load process starts.

So i need to make the Task.Delay method to be inside a Thread so that i can show the progress bar for that delay too.

I tried the following code but it throws me a warning,

//ViewModel Code:

 BackgroundWorker bw;
 async System.Threading.Tasks.Task PutTaskDelay()  //warning here
        {
            bw = new BackgroundWorker();
            IsBusy = true;        // to show the progress bar
            bw.RunWorkerAsync();

            bw.DoWork += async (s, e) =>
            {
                await System.Threading.Tasks.Task.Delay(2000);
            };

            bw.RunWorkerCompleted += (s, e) =>
            {
                IsBusy = false;   // Hide the progress bar
            };
        }

Warning:

The async method lacks await operators and will run synchronously. Consider using the async operator to await non-blocking API calls, or await Task.Run(...) to do CPU-bound work on a backgrond thread.

If there is alternate method let me know.

Upvotes: 2

Views: 723

Answers (2)

moswald
moswald

Reputation: 11667

Your first async isn't required because you don't use await. That's what the warning is telling you.

This is the equivalent to what you've originally posted, with a lot less work involved. Note that async is now required.

async Task PutTaskDelayAsync()   // convention is to name async methods with Async suffix
{
    IsBusy = true;
    await Task.Delay(2000);
    IsBusy = false;
}

Upvotes: 0

usr
usr

Reputation: 171178

BackgroundWorker is obsolete. Use async methods in combination with Task.Run instead and the problem goes away.

Upvotes: 1

Related Questions