0

I am trying to get a simple console app to work. I am stumbling on the await. If i run without await, My PinAuthorization is working, I get the code from twitter, enter it but cannot send a tweet. With the await in front of these commands, I am getting "The await operator can only be used with an async" method.

        var auth = new PinAuthorizer()
        {
            CredentialStore = new InMemoryCredentialStore
            {
                ConsumerKey = ConfigurationManager.AppSettings["consumerKey"],
                ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"]
            },
            GoToTwitterAuthorization = pageLink => Process.Start(pageLink),
            GetPin = () =>
            {
                return (string)Interaction.InputBox("Enter Pin", "Twitter", string.Empty, 10, 10);
            }
        };
        await auth.AuthorizeAsync();

If I remove await, I can run it, but it just cascades from there:

 using (var twitterCtx = new TwitterContext(auth))
 {
     twitterCtx.TweetAsync("Test from thread");
 }

No exceptions are thrown...

I have tried putting this in its own thread, doesnt make any difference. I have tried stuff like

Task task = twitterCtx.TweetAsync("Test from thread");
task.Wait();

Nothing is working. the project is 4.5 vs2013. LinqToTwitterPlc.dll 3.1.2, LinqToTwitter.AspNet.dll 3.1.2

ocuenca
  • 38,548
  • 11
  • 89
  • 102
surfride
  • 11
  • 1
  • microsoft.bcl.build was an old version, i updated to 1.0.21 and I am able to call TweetAsync via Task task = twitterCtx.TweetAsync("Test from thread"); task.Wait(); Question remains, am I actually blocking, why cant I use await? Thanks. – surfride Apr 07 '15 at 18:43

1 Answers1

0

Console apps don't have a synchronization context, so you have to block in Main. That isn't a problem since the concern about blocking in other apps is that they have a UI thread that would cause a deadlock, but not so with Console apps. There's downloadable demos you can look at for examples. Here's how the Console demos in LINQ to Twitter work:

    static void Main()
    {
        try
        {
            Task demoTask = DoDemosAsync();
            demoTask.Wait();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }

        Console.Write("\nPress any key to close console window...");
        Console.ReadKey(true);
    }

From there the rest of the code is async, like this:

    static async Task DoDemosAsync()
    {
       // ...
    }

If you want a synchronization context and/or you dislike the thought of blocking in any type of application, AsyncEx (Formerly Nito.Async) is an excellent library.

Joe Mayo
  • 7,501
  • 7
  • 41
  • 60