no9
no9

Reputation: 6544

Wait for an event to finish (threading)

I need to wait for an event to finish before continuing.

Here is my code:

foreach (KeyValuePair<string, Stream> pair in this.XMLCollection)
{
    ...
    this.eventAggregator.GetEvent<LogToApplicationEvent>().Publish(credentials);
    //wait 
    ...
}

Before continuing I need to wait for "login" event to execute complately. I tried using Task.Factory, but it did not work for me, or I cant use it right...

This code is on presenter, but the event updates the main UI.

//publish
public virtual void Publish(TPayload payload)
{
   base.InternalPublish(payload);
}

Upvotes: 0

Views: 1810

Answers (2)

JvRossum
JvRossum

Reputation: 1008

At least two possible solutions:

BackgroundWorker

Use a BackgroundWorker to execute your code, and use the RunWorkerCompleted event to execute the code that is run after completion.

A BackgroundWorker wraps the event based asynchronous pattern into a very easy to use mechanism, complete with progress reporting and cancellation. See this BackgroundWorker tutorial and this SO answer .

Tasks (.NET 4.0 and above)

Use a Task object, and use the ContinueWith method to define the code that needs to be executed after completion of the first task.

Upvotes: 2

Rohit Vats
Rohit Vats

Reputation: 81233

Event Aggregator publishing and subscribing event pattern is synchronous. You need not to worry about it.

So, it won't resume until its subscribers are finished executing its delegates.

Assumption - You are using inbuilt Event Aggregator class provided by Microsoft.

Upvotes: 2

Related Questions