简体   繁体   中英

C# console app (in a different project) calling async method in class library hangs

I created a class library that makes async calls to MS Graph API. It works great from a console app that lives in the same project. If a add a console app as a new project within the solution and call the async method, the call to Graph just hangs. I figure it may be a deadlock, but I haven't been able to fix it (perhaps I need to re-think the architecture...?). Here is the (scaled down) method in the dll (GraphMail):

//graphClient is an already initiated GraphServiceClient
    public async Task<string> GetMail()
    {
        var messages = await graphClient.Users[user]
            .MailFolders[folder]                
            .Messages                
            .Request()
            .Filter(filter)
            .Select(u => new {
                u.Id,
                u.SentDateTime,
                u.From,
                u.ToRecipients,
                u.Subject,
                u.Body
            })
            .GetAsync();

    return "I'm back";
}

and the call from the Program (each comment is an attempt):

        GraphMail grMail = new GraphMail();

        //var result = grMail().Result;
        //var result = bhMail.GetMail().GetAwaiter().GetResult();
        //var result = Task.Run(() => grMail()).Result;

Thanks for your time.

Your examples seem to be missing the obvious one where you await the result.

Your console app should ensure it is using an async Task Main:

public static async Task Main(string[] args)
{
   GraphMail grMail = new GraphMail();

   var result = await grMail.GetMail();
}

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