受How to: Implement an Asynchronous Service Operation and Building Task Based WCF Services with Task Parallel Library的启发,我正在尝试使用异步执行的操作创建 WCF Web 服务。
这个想法是我有一个方法可以持续从一秒到一分钟,由网页上的按钮调用,我有一个计时器,它调用同一服务中的另一个方法,最终将返回异步操作的状态(工作与否)。
所以我设置了一个虚拟示例,我的异步操作实际上阻塞了我的 Web 服务。
[ServiceContract(Namespace = "")]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Multiple)]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class Service1
{
[OperationContract(AsyncPattern = true, Action = "TestServiceMethod", Name = "TestServiceMethod", ReplyAction = "TestServiceMethodReply")]
public IAsyncResult BeginTestServiceMethod(string request, AsyncCallback callback, object asyncState)
{
var task = new Task<string>((state) =>
{
SpinWait.SpinUntil(() => { return false; }, 5000);
return request;
}, asyncState);
task.ContinueWith((t) => { callback(t); });
task.Start();
return task;
}
public string EndTestServiceMethod(IAsyncResult result)
{
var task = (Task<string>)result;
return task.Result;
}
[OperationContract]
public string OtherTest()
{
return "OtherTest";
}
}
这是我页面上的javascript(点击功能通过点击按钮激活)
function Click() {
var service = new Service1();
service.TestServiceMethod("Dummy", PopWord);
service.OtherTest(PopWord);
}
function PopWord(word) {
alert(word);
}
结果是当我单击按钮时等待 5 秒,然后是“Dummy”和“OtherTest”一个接一个地弹出。预期的行为将是“OtherTest”在 5 秒后弹出“Dummy”。
谁能发现我做错了什么或者建议另一种方法?