C#-返回IEnumerable<;对象>;基于任务的异步调用
我有以下代码:C#-返回IEnumerable<;对象>;基于任务的异步调用,c#,asynchronous,task,C#,Asynchronous,Task,我有以下代码: public class TardiisServiceAsync { private static TardiisServiceAsync instance; public static TardiisServiceAsync Instance { //Singleton get { if (instance == null) {
public class TardiisServiceAsync
{
private static TardiisServiceAsync instance;
public static TardiisServiceAsync Instance
{
//Singleton
get
{
if (instance == null)
{
instance = new TardiisServiceAsync();
}
return instance;
}
}
public const string CACHE_PREFIX_TARDIIS_SERVICE = "TardiisServiceAsync_";
public static Dictionary<string, Tuple<string, object>> clients = new Dictionary<string, Tuple<string, object>>();
public delegate Task<IEnumerable<object>> GetServiceList(object client, string connectionId, TardiisServiceParameters parameters = null);
public async Task<IEnumerable<object>> GetDemographicGroupsDelegateAsync(object client, string connectionId, TardiisServiceParameters parameters = null)
{
//Returns IEnumerable<object> task
var test = Convert(client.GetType().GetMethod("GetDemographicGroupsAsync").Invoke(client, new object[] { connectionId }));
var result = await test;
return (IEnumerable<object>)result;
}
public async Task<IdNameObject[]> GetDemographicGroupsAsync()
{
//This task is called from hight level class
Task<IdNameObject[]> cacheValue = null;
string cacheKey = CACHE_PREFIX_TARDIIS_SERVICE + Membership.GetUser().UserName + "GetDemographicGroupsAsync" + GetMarketCode();
if (ConfigurationManager.AppSettings[ConstantsHelper.FIELD_CONFIG_USE_CACHE_KEY] != null && bool.Parse(ConfigurationManager.AppSettings[ConstantsHelper.FIELD_CONFIG_USE_CACHE_KEY]))
{
if (HttpContext.Current.Cache[cacheKey] == null)
{
var taskResult = InitializeTardiisInstanceAndCallService(GetDemographicGroupsDelegateAsync);
var test = await taskResult;
cacheValue = (Task<IdNameObject[]>)HttpContext.Current.Cache[cacheKey];//This is not implemented yet
}
}
return await cacheValue;
}
public static Task<T> Convert<T>(T value)
{
return Task.FromResult<T>(value);
}
public static EnumHelper.EnumMarketCode GetMarketCode(EnumHelper.EnumMarketCode? marketCode = null)
{
//Returns market code
if (!marketCode.HasValue)
return (EnumHelper.EnumMarketCode.US);
else
return marketCode.Value;
}
private Task<IEnumerable<object>> InitializeTardiisInstanceAndCallService(GetServiceList getServiceList, TardiisServiceParameters parameters = null, EnumHelper.EnumMarketCode? marketCode = null, bool creatingConnectionsForAllCountries = false, string username = "")
{
//Get the instance and call the tardiis correct tardiis service depends on the market code
marketCode = GetMarketCode(marketCode);
MembershipUser membershipUser = Membership.GetUser();
string currentUsername = (membershipUser != null ? membershipUser.UserName : username);
string currentKey = currentUsername + "_" + marketCode;
if (clients.ContainsKey(currentKey))
{
try
{
//check if the connection is still active, or we should reconnect.
return getServiceList(clients[currentKey].Item2, clients[currentKey].Item1, parameters);
}
catch (Exception) { }
}
//At this point there is no connection, we need to open it.
object client = TardiisServiceFactory.GetService(marketCode.Value);
UserDTO userDTO = UserService.Instance.GetByUsername(currentUsername);
TardiisUserDTO tardiisUserDTO = UserService.Instance.GetTardiisUserByUserIdAndMarketCode(userDTO.ID, marketCode.Value.ToString());
if (tardiisUserDTO.TardiisUsername == null)
{
if (creatingConnectionsForAllCountries)
return null;
else
throw new TardiisLoginException("Please enter your credentials");
}
object user = TardiisServiceFactory.GetUser(marketCode.Value, tardiisUserDTO.TardiisUsername, tardiisUserDTO.TardiisPassword);
string connectionId;
try
{
connectionId = (string)client.GetType().GetMethod("InitConnection").Invoke(client, new object[] { user });
}
catch (FaultException ex)
{
// This exception is catched globally by BaseController and prompts the user to enter his
// tardiis credentials again
throw new TardiisLoginException(ex.InnerException.Message, ex);
}
catch (TargetInvocationException ex)
{
// This exception is catched globally by BaseController and prompts the user to enter his
// tardiis credentials again
throw new TardiisLoginException(ex.InnerException.Message, ex);
}
clients[currentKey] = new Tuple<string, object>(connectionId, client);
return getServiceList(clients[currentKey].Item2, clients[currentKey].Item1, parameters);
}
private void AddToCache(string key, object value)
{
HttpContext.Current.Cache.Add(key, value, null, DateTime.Now.AddMinutes(30), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
}
}
公共类TardiisServiceAsync
{
私有静态TardiisServiceAsync实例;
公共静态TardiisServiceAsync实例
{
//独生子女
得到
{
if(实例==null)
{
instance=new TardiisServiceAsync();
}
返回实例;
}
}
public const string CACHE_PREFIX_TARDIIS_SERVICE=“TardiisServiceAsync”;
公共静态字典客户端=新字典();
公共委托任务GetServiceList(对象客户端,字符串connectionId,TardiisServiceParameters=null);
公共异步任务GetDemographicGroupsDelegateAsync(对象客户端,字符串连接ID,tardIsServiceParameters=null)
{
//返回IEnumerable任务
var test=Convert(client.GetType().GetMethod(“GetDemographicGroupsAsync”).Invoke(客户端,新对象[]{connectionId}));
var结果=等待测试;
返回(IEnumerable)结果;
}
公共异步任务GetDemographicGroupsAsync()
{
//此任务是从高级类调用的
任务cacheValue=null;
字符串cacheKey=CACHE_PREFIX_TARDIIS_SERVICE+Membership.GetUser().UserName+“GetDemographicGroupsAsync”+GetMarketCode();
if(ConfigurationManager.AppSettings[ConstantsHelper.FIELD\u CONFIG\u USE\u CACHE\u KEY]!=null&&bool.Parse(ConfigurationManager.AppSettings[ConstantsHelper.FIELD\u CONFIG\u USE\u CACHE\u KEY]))
{
if(HttpContext.Current.Cache[cacheKey]==null)
{
var taskResult=InitializeTaDiiSinstanceAndCallService(GetDemographicGroupsDelegateAsync);
var测试=等待任务结果;
cacheValue=(任务)HttpContext.Current.Cache[cacheKey];//这尚未实现
}
}
返回等待缓存值;
}
公共静态任务转换(T值)
{
返回Task.FromResult(值);
}
公共静态EnumHelper.EnumMarketCode GetMarketCode(EnumHelper.EnumMarketCode?marketCode=null)
{
//返回市场代码
如果(!marketCode.HasValue)
return(EnumHelper.EnumMarketCode.US);
其他的
返回marketCode.Value;
}
私有任务初始值SetAdiInsistanceAndCallService(GetServiceList GetServiceList,TardiInserviceParameters参数=null,EnumHelper.EnumMarketCode?marketCode=null,bool creatingConnectionsForAllCountries=false,字符串username=”“)
{
//获取实例并调用tardiis正确的tardiis服务,具体取决于市场代码
marketCode=GetMarketCode(marketCode);
MembershipUser MembershipUser=Membership.GetUser();
字符串currentUsername=(membershipUser!=null?membershipUser.UserName:用户名);
字符串currentKey=currentUsername+“”+marketCode;
if(clients.ContainsKey(currentKey))
{
尝试
{
//检查连接是否仍然处于活动状态,或者我们应该重新连接。
返回getServiceList(客户端[currentKey].Item2,客户端[currentKey].Item1,参数);
}
捕获(异常){}
}
//此时没有连接,我们需要打开它。
objectclient=TardiisServiceFactory.GetService(marketCode.Value);
UserDTO UserDTO=UserService.Instance.GetByUsername(currentUsername);
TardiIsUserTo TardiIsUserTo=UserService.Instance.GetTardiIsUserByUserId和marketCode(userDTO.ID,marketCode.Value.ToString());
if(tardiisUserTo.TardiisUsername==null)
{
if(为所有国家/地区创建连接)
返回null;
其他的
抛出新的TardiIsEngineException(“请输入您的凭据”);
}
object user=TardiisServiceFactory.GetUser(marketCode.Value、tardiisUserTo.TardiisUsername、tardiisUserTo.TardiisPassword);
字符串连接ID;
尝试
{
connectionId=(string)client.GetType().GetMethod(“InitConnection”).Invoke(客户端,新对象[]{user});
}
捕获(FaultException-ex)
{
//BaseController全局捕获此异常,并提示用户输入其
//塔迪又来了
抛出新的tardiisLogineException(例如InnerException.Message,例如);
}
捕获(目标异常)
{
//BaseController全局捕获此异常,并提示用户输入其
//塔迪又来了
抛出新的tardiisLogineException(例如InnerException.Message,例如);
}
clients[currentKey]=新元组(connectionId,client);
返回getServiceList(客户端[currentKey].Item2,客户端[currentKey].Item1,参数);
}
私有void AddToCache(字符串键、对象值)
{
HttpContext.Current.Cache.Add(key,value,null,DateTime.Now.AddMinutes(30),Cache.NoSlidingExpiration,CacheItemPriority.Normal,null);
}
}
我收到以下错误消息:
无法将“System.Threading.Tasks.Task[System.object]类型的对象强制转换为“System.Collections.Generic.IEnumerable1[System.object]”类型。
该任务的结果是一个类型类[]
如何在call方法上作为任务返回
这是另一个类的“副本”,该类具有类似的逻辑,但以同步方式。想法是改变一些方法
因此,它们可以同步运行
谢谢大家! public异步任务GetDemographicGroupsDelegateAsync(对象客户端,字符串连接ID,tardIsServiceParameters=null)
public async Task<IEnumerable<object>> GetDemographicGroupsDelegateAsync(object client, string connectionId, TardiisServiceParameters parameters = null)
{
var test = Convert(client.GetType().GetMethod("GetDemographicGroupsAsync").Invoke(client, new object[] { connectionId }));
var result = await test;
var resultado = test.Result;
return Convert(new List<Object>{resultado});
}
{
var test=Convert(client.GetType().GetMethod(“GetDemographicGroupsAsync”).Invoke(客户端,新对象[]{connectionId}));
var结果=等待测试;
弗吉尼亚州
public async Task<IEnumerable<object>> GetDemographicGroupsDelegateAsync(object client, string connectionId, TardiisServiceParameters parameters = null)
{
var test = Convert(client.GetType().GetMethod("GetDemographicGroupsAsync").Invoke(client, new object[] { connectionId }));
var task = await test;
var taskResult = await task;
return taskResult.Cast<object>();
}