1

I have simple code which I want to be executed asynchrounously:

public async Task EncryptAsync()
{
    for (int i = 0; i < 10; i++)
    {
        // shift bytes
        // column multiplication
        // and so on
    }
}

That is the way I call above method:

private async void Encryption()
{
    ShowBusyIndicator();

    await encryptor.EncryptAsync();

    HideBusyIndicator();
}

The point is, when I add await Task.Delay(1000); in this method, busi indicator is shown, but after 1 sec, application locks and waits SYNCHRONOUSLY for encryption complete. If I remove Task.Delay, application lock and unlocks after operation finished.

How to use properly await and asyc in my case? I want simply execute method encryptor.EncryptAsync() asynchronously.

5
  • Note the compiler warning that your code gives. Commented Jun 2, 2013 at 19:57
  • 3
    Cryptography is hard. Do not invent your own encryption. Commented Jun 2, 2013 at 19:59
  • It's just a feature for shiny and fancy looking :P Commented Jun 2, 2013 at 20:01
  • That's even worse. Do not mislead your users into thinking that you will actually protect their data. Creating a real security product along these lines is an extremely complicated task. Read Bruce Schneier's blog. Commented Jun 2, 2013 at 20:06
  • It's just a student's application. Simple, without any complex logic and secure systems. Commented Jun 2, 2013 at 20:12

1 Answer 1

4

The async / await keywords do not allow you to create new asynchrony; instead, they simply allow you to wait for an existing asynchronous operation to complete.

You want to run your CPU-bound operation on a background thread to avoid blocking the UI.
To do that, call the synchronous blocking method inside a lambda passed to Task.Run().

You can then use await to wait for the resulting asynchronous operation (a Task instance).

Sign up to request clarification or add additional context in comments.

11 Comments

Try msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx that is very basic article and good sample that contains waiting on async with Task that return int
I wrote: private async void Encryption() { ShowBusyIndicator(); await Task.Run(() => encryptor.EncryptAsync()); HideBusyIndicator(); } Works!
Why do you await on Task.Run ?
@ilansch: To make HideBusyIndicator() run after the task finishes.
Pardon me asking but if you await a task, doesnt it start the task and wait for it to complete before heading the next line ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.