在 Page_Load 中调用异步方法 [英] Call Async Method in 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");
}
如何在 Page_Load
上调用 async
方法?
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");
}
或者,如果您不希望它成为 async
:
Or if you don't want it to be async
:
protected void Page_Load(object sender, EventArgs e)
{
SendTweetWithSinglePicture("test", "path").Wait();
}
这确实需要您的 async
方法返回 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屋!