简体   繁体   中英

Question regarding appropriate use for Task in C#

I have a question regarding Task. I have a WCF app which has a method ReceiveEmpInfo which will be called from a client app.

WCF Server app:

public void ReceiveEmpInfo(string EmpName, string EmpId)
{
    DifferentClass.SaveEmpToDB(string EmpName, string EmpId);
    return;
}

My requirement is I want to return this method call ( ReceiveEmpInfo() ) once I call the method SaveEmpToDB() , I don't want to hold the client call until the SaveEmpToDB() method saves the data to the database. I'm thinking of using Task, but I'm not sure whether it will solve my requirement.

Please give me your suggestions.

Thanks, Joe

Yes, it will. Once you call Task.Start() your WCF method can return and the task will run in the "background". You have to be very careful, especially if you're running this WCF service inside of IIS. If these tasks are very long running and the IIS application pool shuts down (or gets restarted) your task is going to get whacked [potentially] in the middle of its work.

BTW: I'm assuming you're referring to: System.Threading.Tasks.Task

使用回调,并对db等执行异步调用,请参阅示例http://msdn.microsoft.com/en-us/library/ca56w9se.aspx

This is a lot like this post:

How to make a call to my WCF service asynchronous?

I think the links in the popular answer should help.

If this is a one-way fire-and-forget operation you can simply make the operation one-way . This will not block the client for the duration of the method execution.

[ServiceContract]
interface ISomeContract
{
   [OperationContract(IsOneWay = true)]
   void ReceiveEmpInfo(string EmpName, string EmpId)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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