在Page_Load中调用异步方法 [英] Call Async Method in Page_Load

查看:312
本文介绍了在Page_Load中调用异步方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

static async void SendTweetWithSinglePicture(string message, string image)
{
    var auth = new SingleUserAuthorizer
    {
        CredentialStore = new SingleUserInMemoryCredentialStore
        {
            ConsumerKey = "",
            ConsumerSecret = "",
            AccessToken = "",
            AccessTokenSecret = ""
        }
    };

    var context = new TwitterContext(auth);

    var uploadedMedia = await context.UploadMediaAsync(File.ReadAllBytes(@image));
    var mediaIds = new List<ulong> { uploadedMedia.MediaID };

    await context.TweetAsync(
        message,
        mediaIds
    );
}
protected void Page_Load(object sender, EventArgs e)
{
    SendTweetWithSinglePicture("test", "path");
}

如何调用 async Page_Load 上的$ c>方法?

How can I call a async method on Page_Load?

推荐答案

问题是想要使 Page_Load 方法异步。如果是这样的话:

The question is if you want to make the Page_Load method async or not. If so:

protected async void Page_Load(object sender, EventArgs e)
{
    await SendTweetWithSinglePicture("test", "path");
}

或者如果您不希望它为异步

Or if you don't want it to be async:

protected void Page_Load(object sender, EventArgs e)
{
    SendTweetWithSinglePicture("test", "path").Wait();
}

这确实需要您的异步返回 Task 一如既往的方法!(事件处理程序除外)

This does require your async method to return Task as it always should! (except event handlers)

此问题可能是该方法在呈现页面之前未完成。如果需要,最好使该方法同步,或使用 Page.RegisterAsyncTask Page.ExecuteRegisteredAsyncTasks 。实际上,这也会冻结 Page_Load 方法。

The problem with this might be that the method doesn't complete before rendering the page. If it has to, you'd better make the method synchronous, or register the task using Page.RegisterAsyncTask and Page.ExecuteRegisteredAsyncTasks. Effectively this will freeze the Page_Load method too.

protected void Page_Load(object sender, EventArgs e)
{
    PageAsyncTask t = new PageAsyncTask(SendTweetWithSinglePicture("test", "path"));

    // Register the asynchronous task.
    Page.RegisterAsyncTask(t);

    // Execute the register asynchronous task.
    Page.ExecuteRegisteredAsyncTasks();
}

这篇关于在Page_Load中调用异步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆