简体   繁体   English

从WCF服务调用方法异步并立即返回

[英]Calling method async from WCF service and return immediately

A third party is calling our WCF service. 第三方正在致电我们的WCF服务。 The caller wants confirmation, that the sent records have been received and stored, within a small timeframe. 呼叫者希望在短时间内确认已发送的记录已被接收并存储。

The records that are stored need some lenghty processing. 存储的记录需要一些冗长的处理。 Can the processing be executed async, right after storing the records, so the confirmation can be send immediately? 可以在存储记录后立即执行异步处理,以便可以立即发送确认吗?

Ofcourse there can be a separate process that does the processing, but the question is whether I can combine storage and processing without timing out. 当然,可以有一个单独的进程来执行处理,但是问题是我是否可以在不超时的情况下将存储和处理结合起来。

Update: 更新:
It looks like this works: 看起来像这样:

var aTask = new Task(myService.TheMethod);
aTask.Start();

return aVariableAsync;

Or is this a very bad idea to do from within my WCF host, because.. ? 还是在我的WCF主机中执行此操作是一个非常糟糕的主意,因为..?

You can set "AsyncPattern" to true on the OperationContract attribute as described on MSDN . 您可以按照MSDN上的说明在OperationContract属性上将“ AsyncPattern”设置为true。

You can then control the concurrency using the following attribute on the service method: 然后,可以在服务方法上使用以下属性来控制并发性:

[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple)]

Yes it can be done. 是的,它可以做到。 I dont have a ton of experience with it, but this is a snippet of some code showing that. 我没有大量的经验,但这是一些显示该代码的片段。 The service calls this method on the controller that saves an xml message to the hard drive and then kicks off a separate task to process it into MongoDB and returns a message back to the service that it was successfully saved. 服务在控制器上调用此方法,该方法将xml消息保存到硬盘驱动器,然后启动一个单独的任务以将其处理到MongoDB中,并将消息返回到已成功保存的服务。

    public string SaveTransaction(XElement pTransactionXml, string pSavePath)
    {

        //save the transaction to the drive locally
        pTransactionXml.Save(pSavePath);

        ...

        var mongoTask = Task.Run(async () =>
        {
            await SendXMLFilesToMongo(pSavePath);
        });

        return response.WithResult("Successfully saved to disk.");
    }



    public virtual async Task<int> SendXMLFilesToMongo(string pSavePath)
    {
         //call the code to save to mongo and do additional processing
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM