线程模式:链接和循环

时间:2009-09-16 10:56:50

标签: multithreading design-patterns

我需要使用WCF API将数据保存到数据库中。通常,我会使用链接,如下例所示:

    IClientBroker clientBroker = UIContext.CreateWcfInterface<IClientBroker>("Data/ClientBroker.svc");
    clientBroker.BeginSetClientBusinessName(_client.ID, businessName, (result) =>
        {
            _client = ((IClientBroker)result.AsyncState).EndSetClientBusinessName(result);

                    clientBroker.BeginSetClientAddress(_client.ID, addressObservableCollection, postcodeZip, (result2) =>
                {
                    _client = ((IClientBroker)result2.AsyncState).EndSetClientAddress(result2);

                            clientBroker.BeginSetClientTelephone(_client.ID, telephone, (result3) =>
                        {
                            _client = ((IClientBroker)result3.AsyncState).EndSetClientTelephone(result3);

                                    clientBroker.BeginSetClientFax(_client.ID, fax, (result4) =>
                                {
                                            _client = ((IClientBroker)result4.AsyncState).EndSetClientFax(result4);

                                            if (customFields.Save(validationSummaryBridge))
                                            {
                                                CloseWindow(true, "ClientID=" + _client.ID.ToString());
                                            }
                                            else
                                            {
                                                validationSummary.Errors.Add(new ValidationSummaryItem("Failed to save Custom Fields"));
                                            }
                                }, clientBroker);
                        }, clientBroker);
                }, clientBroker);
        }, clientBroker);
}

这给了我我需要的虚假同步行为,以便及时抛出异常,我可以对验证事件做出反应。

但是,当我有一个要保存的字段循环时,这不能很好地映射。例如,哪种模式最好保存以下“自定义字段”列表,其中每个自定义字段必须使用单个WCF调用保存?

    ICustomFieldsBroker customFieldsBroker = UIContext.CreateWcfInterface<ICustomFieldsBroker>("Data/CustomFieldsBroker.svc");
    foreach (CustomField customField in _customFields)
    {   
        string newValue=_customFieldControlDictionary[customField].CustomField.Value;
                customFieldsBroker.BeginSetCustomFieldValueForItem(DataTypeID, DataItemID, customField.Key, newValue, (result) =>
            {
                        ((ICustomFieldsBroker)result.AsyncState).EndSetCustomFieldValueForItem(result);
            }, customFieldsBroker);
    }

在上面的例子中,这只会引发5个对WCF API /线程的请求,这些请求可能会在表单关闭后返回。我需要他们“排队”,所以我可以列出他们的状态并返回表格。

非常感谢。

不要让WCF分散您的注意力,但如果您有任何意见,请告诉我。 :)