在Page_Load中调用异步方法

时间:2015-12-10 14:30:53

标签: c# asp.net .net async-await

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方法?

3 个答案:

答案 0 :(得分:3)

问题是您是否要使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();
}

答案 1 :(得分:0)

您应该使用PageAsyncTask。它在MSDN页面中有样本。

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

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

正如我在MSDN页面上指出的样本和解释非常好。

答案 2 :(得分:0)

试试这个:

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