0

I have the following code and while when calling it the expected way it works, it locks when I try to directly access the Result property of the task.

I wasn't expecting this, especially when I specify ConfigureAwait(false). Also I'm not sure if I should keep a reference of the instance (and dispose where?) returned by cancellationToken.Register method, which implements IDisposable.

public async void SomeUIThreadHandlerMethod()
{
    // works
    var contactsWorks = await instance.ScanContactsAsync(CancellationToken.None);
    // Locks
    var contactsLocks = instance.ScanContactsAsync(CancellationToken.None).Result;
    // Locks
    var contactsLocks = instance.ScanContactsAsync(CancellationToken.None).GetAwaiter().GetResult();
}


public async Task<ICollection<Contact>> ScanContactsAsync(CancellationToken cancellationToken)
{
    var contactsCompletion = new TaskCompletionSource<ICollection<Contact>>();

    try
    {
        cancellationToken.Register(state => ((TaskCompletionSource<ICollection<Contact>>)state).TrySetCanceled(), contactsCompletion);

        var contacts = new Contacts();

        contacts.SearchCompleted += (_, args) => contactsCompletion.TrySetResult(args.Results.ToArray());

        contacts.SearchAsync(string.Empty, FilterKind.None, null);
    }
    catch (Exception ex)
    {
        contactsCompletion.TrySetException(ex);
    }

    return await contactsCompletion.Task.ConfigureAwait(false);
}
Pinco Pallino
  • 916
  • 1
  • 6
  • 18
  • 2
    What is unclear about this? It's the classic ASP.NET deadlock which, apparently, you know about. – usr Sep 24 '15 at 16:10
  • 1
    You literally just needed to put your question into Google to get your answer. – Servy Sep 24 '15 at 16:10
  • As you can see "ConfigureAwait(false)" is called wherever it is possible and no blocking code exists anywhere. – Pinco Pallino Sep 24 '15 at 22:39

0 Answers0