调用一个又一个方法,同时在c#中的一个方法中使用异步
本文关键字:方法 一个 异步 调用 一个又一个 | 更新日期: 2023-09-27 18:13:12
我需要在执行objMy_HelloWorldCompleted
后调用CallServiceCompleted()
方法。当前在执行objMy_HelloWorldCompleted
之前,CallServiceCompleted正在被调用。
protected void btnCheck_Click(object sender, EventArgs e) {
Task taskA = Task.Factory.StartNew(() => CallServices());
taskA.Wait();
//CallServices();
if(taskA.IsCompleted ) {
CallServiceCompleted();
}
}
private void CallServiceCompleted() {
lblServicesCompleted.Text = "Work Completed";
}
private void CallServices() {
myITSSEVR.myserv objMy = new myITSSEVR.myserv();
string s = "New Line";
objMy.HelloWorldCompleted += objMy_HelloWorldCompleted;
objMy.HelloWorldAsync(s);
}
void objMy_HelloWorldCompleted(object sender, myITSSEVR.HelloWorldCompletedEventArgs e) {
string s2 = (string)e.UserState;
lblName.Text = e.Result.ToString();
}
这是Page。RegisterAsyncTask处理点击事件:
protected void btnAsyncPostBack_Click(object sender, EventArgs e) {
RegisterAsyncTask(new PageAsyncTask(MyMethodAsync));
}
private async Task MyMethodAsync(object sender, EventArgs e, CancellationToken cancellationToken) {
var sum = await GetSumAsync();
lblMessage.Text = string.Format("Sum = {0}", sum);
}
链接到论坛主题。
在StackOverflow上也有类似的问题