简体   繁体   中英

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);
}

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM