在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");
}
如何调用 async $ c
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 $ c $注册该任务c>。实际上,这也会冻结
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屋!