Trying to make a method wait for internal events to finish processing

I am new to C # async / await and encounter some problems when trying to work with the async method. I have a collection:

private IList<IContactInfo> _contactInfoList

And async method:

public async Task<IList<IContactInfo>> SelectContacts()
{
    _contactInfoList = new List<IContactInfo>();
    ContactsSelector selector = new ContactsSelector();
    selector.ShowPicker();

    selector.ContactsSelected += (object sender, ContactsSelectorEventArgs e) =>
    {
        this._contactInfoList = e.Contacts;                
    };

    return _contactInfoList;
}

Contact selector - , "" ContactsSelected. e.Contacts SelectContacts() async. : _contactInfoList , ContactsSelected . , async/await , , .

+4
1

, . TaskCompletionSource .

public static Task<IList<IContactInfo>> WhenContactsSelected(
    this ContactsSelector selector)
{
    var tcs = new TaskCompletionSource<IList<IContactInfo>>();
    selector.ContactsSelected += (object sender, ContactsSelectorEventArgs e) =>
    {
        tcs.TrySetResult(e.Contacts);
    };
    return tcs.Task;
}

, , , , , :

public Task<IList<IContactInfo>> SelectContacts()
{
    ContactsSelector selector = new ContactsSelector();
    selector.ShowPicker();

    return selector.WhenContactsSelected();
}

. -, ; . SelectContacts , . , , . , await, async. await WhenContactsSelected, async , .

+4

All Articles