Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a function when a Task finishes

I have want to run a function asynchronously to prevent UI freezing. Here the the button click event.

private void btnEncrypt_Click(object sender, EventArgs e)
{
    // Create new Vigenere object instant
    cryptor = new Vigenere(txtPassword.Text, txtBox.Text);

    // Run encryption async
    Task<string> T = new Task<string>(cryptor.Encrypt);
    T.Start();
}

Now I want the following function to be called when the Task T finishes with it's return value as a parameter like this:

private void Callback(string return_value)
{
    txtBox.Text = return_value

    // Some other stuff here
}

How to achieve this?

like image 314
Xbyte Finance Avatar asked Dec 01 '15 17:12

Xbyte Finance


1 Answers

What you could do is use the ContinueWith(Action<Task>) method.

So you would have something like

Task<string> t = new Task<string>(cryptor.Encrypt);
T.Start();

Task continuationTask = t.ContinueWith((encryptTask) => {
    txtBox.Text = encryptTask.Result;
    ...
})

Effectively this just says do the action after the current task completes, completion could be successful running, faulting or exiting early due to cancellation. You would likely want to do some error handling to make sure you didn't try to use the result of a cancelled or faulted task.

like image 110
Stephen Ross Avatar answered Sep 20 '22 05:09

Stephen Ross