How to take what was returned from a Task

Asked

Viewed 68 times

0

I have following code:

                List<UserItem> items = null;
                Task taskCreateItems = new Task(() => items = DeliverItems(Session, Item.GetBaseItem(i), (priceAmount * ((Item.Items.Count > 1) ? Item.Items[i] : Item.Amount)), ExtraData, (Page.MinRank > 1), Item.songID));
                taskCreateItems.Start();

This is the old code:

var items = DeliverItems(Session, Item.GetBaseItem(i), (priceAmount * ((Item.Items.Count > 1) ? Item.Items[i] : Item.Amount)), ExtraData, (Page.MinRank > 1), Item.songID));

With old code I could get what was returned, eg items.Count, items[0], but in new code using Task I don’t know how to do this.

  • 1

    You look like this doesn’t solve what you expect it to solve, but you tried taskCreateItems.Result?

2 answers

1

After the taskCreateItems.Start();

Place var str_recebida = await taskCreateItems;

Don’t forget to put the function as Async for example:

private async void btn_Send_Click(object sender, EventArgs e){}

0


If you are trying to make this instruction work without interrupting the running code operation, I recommend using a TaskFactory.

Observing: if it is a STA/Windows Forms application, put this line in the application loading method:

Control.CheckForIllegalCrossThread = false;
// isso irá desativar as verificações de acesso aos membros feitos
// por threads em que os invocadores não fazem parte do Thread atual.

After that, do it in your code:

// declare a variável onde será utilizada pelo thread
List<UserItem> items = null;

// isso mesmo. Declare esse void dentro do void que você está
// trabalhando. isso será um sub-void.
void editarItems () {
     items = DeliverItems(Session, Item.GetBaseItem(i), (priceAmount * ((Item.Items.Count > 1) ? Item.Items[i] : Item.Amount)), ExtraData, (Page.MinRank > 1), Item.songID));
}

// inicie o thread
new System.Threading.Tasks.TaskFactory().StartNew(editarItems);

See working on .Net Fiddle, together with an excerpt indicating whether the method has been executed or not.


Important: the declaration of sub-voids only works if you are using the compiler of C# Roslyn 2.0 or higher, which is installed by default in Visual Studio 2017 and 2019.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.