C# 在c中调用异步Web服务#
在将结果返回给用户后,我需要调用C#webservice中的一些函数,因此我打算使用单向方法 我在同一个项目上创建了两个Web服务,如下所示: 第一:呼叫服务:C# 在c中调用异步Web服务#,c#,web-services,asynchronous,C#,Web Services,Asynchronous,在将结果返回给用户后,我需要调用C#webservice中的一些函数,因此我打算使用单向方法 我在同一个项目上创建了两个Web服务,如下所示: 第一:呼叫服务: public class Caller : System.Web.Services.WebService { [WebMethod] public string HelloWorld() { var bg = new Background(); bg.HelloWorldBG(); return "Hello
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()的执行之前不会返回。您可以通过使用方法启动新任务来运行从线程池中挑选的单独线程:
var bg = new Background();
Task.Factory.StartNew(bg.HelloWorldBG);
return "Hello World";
当然,因为您只是像调用任何其他类一样调用一个类的方法(HelloWorld)(从编译器的角度来看,它的基类是否是web服务并不重要)。使用threadpool异步调用它(如果.NET 4+,则调用任务)。有关执行异步Web服务的所有详细信息,请参阅此链接