如何在If条件下继续使用C#中的Task

时间:2016-06-30 07:41:12

标签: c# wcf asynchronous async-await

我在.NET应用程序中实现了wcf客户端。我的问题是如何确保在任务>之后调用条件。完成了?

  private List<MarketingCampaign> _GetAllCampaignTypeList()
    {
        List<MarketingCampaign> _MarketingCampaignList = null;

        Task<List<MarketingCampaignTypeData>> _MarketingCampaignTypeDataList = _MarketingCampaignTypeClientObject.GetAllCampaignTypes();

        ??? // how can I use continue with or Task.wait all in following if condition

        if(_MarketingCampaignTypeDataList!=null)
        {
           // code
        }

        return _MarketingCampaignList;
    }

上面的代码正在调用类

  public async Task<List<App.Client.Proxies.MarketingCampaignTypeServiceRef.MarketingCampaignTypeData>> GetAllCampaignTypes()
    {

        var task  = Task<List<App.Client.Proxies.MarketingCampaignTypeServiceRef.MarketingCampaignTypeData>>.Factory.StartNew(() => {
                                            return _MarketingCampaignTypeClient.GetAllCampaignTypes();
                                      });

        return await task.ConfigureAwait(false);

    }

1 个答案:

答案 0 :(得分:2)

我相信你需要这样的东西:

async Task<List<MarketingCampaign>> GetAllCampaignTypeList()
{
    List<MarketingCampaign> campaignList = null;

    List<MarketingCampaignTypeData> campaignTypeList = await _MarketingCampaignTypeClientObject.GetAllCampaignTypes();

    if(campaignTypeList != null)
    {
       // do whatever you need to convert campaignTypeList to campaignList
    }

    return campaignList;
}

此外,您在await方法中不需要GetAllCampaignTypes,只需返回任务即可。如果没有正当理由,我建议你不要使用Task.Factory.StartNew。请改为使用Task.Runhttp://blog.stephencleary.com/2013/08/startnew-is-dangerous.html