在c#中调用异步Web服务

时间:2013-09-05 13:19:43

标签: c# web-services asynchronous

我需要在将结果返回给用户后在C#webservice中调用一些函数,所以我打算使用OneWay方法。

我在同一个项目上创建了2个webservices,如下所示: 1st:来电服务:

public class Caller : System.Web.Services.WebService {

[WebMethod]
public string HelloWorld() {

    var bg = new Background();
    bg.HelloWorldBG();
    return "Hello World";
}
}

第二个要在后台调用的服务:

[ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples", SessionMode = SessionMode.Required)]
public class Background : System.Web.Services.WebService {

[SoapDocumentMethod(OneWay = true)]
[WebMethod(EnableSession = true)]
public void HelloWorldBG()
{
    Thread.Sleep(60000);
    var file = @"D:\testHello.txt";
    File.WriteAllText(file, "Hello World");
}    

}

但是当我调用HelloWorld()时,它在完成HelloWorldBG()的执行之前没有返回

1 个答案:

答案 0 :(得分:1)

您可以通过使用您的方法启动新任务来运行从线程池中挑出的单独线程:

var bg = new Background();
Task.Factory.StartNew(bg.HelloWorldBG);
return "Hello World";