c# - 任务异步困惑

标签 c# wcf asynchronous

我被要求将 WCF 服务调用从同步转换为异步,但该调用似乎仍在同步运行。我做错了什么?

这是我的服务契约(Contract)

[ServiceContract]
public interface ICredentialReplication
{
    /// <summary>
    /// Updates the store database with credential data
    /// </summary>
    /// <param name="credentials">the credential data to update</param>
    [OperationContract]
    Task ReplicateDataAsync(CredentialDataList credentials);

这是我的实现

/// <summary>
    /// Copy the credential data to the stores
    /// </summary>
    /// <param name="credentials">The credential data to copy</param>
    public async Task ReplicateDataAsync(CredentialDataList credentials)
    {
        var task = Task.Factory.StartNew(() => UpdateData(credentials));
        await task;  
    }

我已经在客户端中设置了“生成异步操作”标志来生成代理类,并使用以下代码调用服务(服务调用位于最后)

 foreach (var store in storedic)
            {
                // call the replication service for that store                    
                CredentialDataList credentialData = new CredentialDataList();
                List<CredentialData> credentialList = new List<CredentialData>();

                foreach (var payroll in store)
                {
                    CredentialData cred = this.ExtractCredentialData(data, pinData, payroll);
                    credentialList.Add(cred);                       
                }

                credentialData.CredentialList = credentialList.ToArray();
                credentialData.PermissionList = permDataList;
                credentialData.PermissionTypeList = permTypeDataList;   

                // then call the service
                this._client.ReplicateData(credentialData);     
            }               

我原以为在调试器中单步执行此循环应该立即返回,但它会等待服务调用完成后再返回。我错过了什么吗?

最佳答案

您似乎正在使用客户端 API 的同步版本,而不是异步版本:

this._client.ReplicateData(credentialData); 

而不是使用 async over sync anti-pattern ,我建议改用 API 的同步版本。

使用 WCF 来 generate a task based operation您可以等待:

Wcf settings

var replicatedData =  await _client.ReplicateDataAsync();

关于c# - 任务异步困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28502190/

相关文章:

scala future 错误为 "Don' t 直接调用 `Awaitable` 方法,请使用 `Await` 对象。”

php - 异步使用 Guzzle promises

c# - 如何获得与 UnityEngine.SystemInfo.deviceUniqueIdentifier 中相同的硬件 ID?

c# - 类库 - 引用 - 复制本地的可重用性?

c# - 将 WIF STS token 与 WCF 结合使用

c# - IIS 中的 WCF,http 基本身份验证 - Windows 用户 "security"含义

android - 回调 hell : Sequencing RESTful Volley requests? RxAndroid?

c# - 使用javascript更改输入值

c# - 使用 Windows Installer 安装时如何更改应用程序的 exe.config 文件

c# - 通过 Remoting/WCF 在远程计算机上部署和执行代码