linqtotwitter await auth.AuthorizeAsync();

时间:2015-04-07 18:03:23

标签: c# asynchronous linq-to-twitter

我正在尝试使用一个简单的控制台应用程序。我在等待中磕磕绊绊。如果我没有等待,我的PinAuthorization正在运行,我从twitter获取代码,输入它但不能发送推文。等待在这些命令前面,我得到“await运算符只能与async一起使用”方法。

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

如果我删除await,我可以运行它,但它只是从那里级联:

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

不会抛出异常......

我试过把它放在自己的线程中,没有任何区别。我尝过像

这样的东西
Task task = twitterCtx.TweetAsync("Test from thread");
task.Wait();

什么都没有用。该项目是4.5 vs2013。 LinqToTwitterPlc.dll 3.1.2,LinqToTwitter.AspNet.dll 3.1.2

1 个答案:

答案 0 :(得分:0)

控制台应用没有同步上下文,因此您必须在Main中阻止。这不是问题,因为关注其他应用程序中的阻塞是因为他们有一个可能导致死锁的UI线程,但对于Console应用程序则不然。您可以查看downloadable demos示例。以下是LINQ to Twitter中控制台演示的工作原理:

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

从那里剩下的代码是异步的,如下所示:

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

如果你想要一个同步上下文和/或你不喜欢在任何类型的应用程序中阻塞,AsyncEx(以前的Nito.Async)是一个很好的库。

相关问题