在Page_Load中调用异步方法

本文关键字:调用 异步方法 Load Page | 更新日期: 2023-09-27 18:26:22

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

如何在Page_Load上调用async方法?

在Page_Load中调用异步方法

问题是您是否要使Page_Load方法异步。㞖:

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

或者,如果您不希望它被async

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

这确实需要您的async方法像往常一样返回Task(事件处理程序除外(

这样做的问题可能是该方法在呈现页面之前未完成。如果必须这样做,最好使该方法同步,或使用 Page.RegisterAsyncTaskPage.ExecuteRegisteredAsyncTasks 注册任务。实际上,这也将冻结Page_Load方法。

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

你应该使用 PageAsyncTask。它在 MSDN 页面中有示例。

// Register the asynchronous task.
Page.RegisterAsyncTask(new PageAsyncTask(SendTweetWithSinglePicture(message, image));
// Execute the register asynchronous task.
Page.ExecuteRegisteredAsyncTasks();

正如我指出的那样,MSDN页面上的示例和解释非常好。

试试这个:

 public void Page_Load(object sender, EventArgs e)
{
    RegisterAsyncTask(new PageAsyncTask(LoadSomeData));
}
public async Task LoadSomeData()
{
    var clientcontacts = Client.DownloadStringTaskAsync("api/contacts");
    var clienttemperature =     Client.DownloadStringTaskAsync("api/temperature");
    var clientlocation = Client.DownloadStringTaskAsync("api/location");
    await Task.WhenAll(clientcontacts, clienttemperature, clientlocation);
    var contacts =     Newtonsoft.Json.JsonConvert.DeserializeObject<List<Contact>>(await clientcontacts);
    var location = Newtonsoft.Json.JsonConvert.DeserializeObject<string>(await clientlocation);
    var temperature = Newtonsoft.Json.JsonConvert.DeserializeObject<string>(await clienttemperature);
    listcontacts.DataSource = contacts;
    listcontacts.DataBind();
    Temparature.Text = temperature;
    Location.Text = location;
}