C# Rabbitmq RPC模式服务器超时解决方案

利用2个task实现,看红字,直接看代码
public string Call(string rpc_queue, byte[] obj)
{
string rstr = “no”;
var channel = this.GetModel(RpcChannel); channel.ContinuationTimeout = TimeSpan.FromSeconds(10);
channel.BasicPublish(exchange: “”, routingKey: rpc_queue, basicProperties: props, body: obj);
channel.BasicConsume(consumer: consumer, queue: replyQueueName, autoAck: true);
Task[] tasks = new Task[2];
tasks[0] = Task.Run(async () =>
{
await Task.Delay(6000);//超时
respQueue.Add(rstr);
//respQueue.CompleteAdding();
});
tasks[1] = Task.Run(() =>
{
rstr = respQueue.Take();
});
try
{
Task.WaitAll(tasks);
}
catch (AggregateException ae)
{
foreach (var ex in ae.InnerExceptions)
Console.WriteLine(” {0}: {1}”, ex.GetType().Name, ex.Message);
}
return rstr;
}

C#动态编译表达式

下面是原始方案
public object ComplierCode(string expression, ILogService logService, out string errorString)
{
string code = WrapExpression(expression);
object retvalue = null;
errorString = “”;
CSharpCodeProvider csharpCodeProvider = new CSharpCodeProvider();
try
{
//编译的参数
CompilerParameters compilerParameters = new CompilerParameters
{
CompilerOptions = “/t:library”,
GenerateInMemory = true
};
//开始编译
CompilerResults compilerResults = csharpCodeProvider.CompileAssemblyFromSource(compilerParameters, code);
if (compilerResults.Errors.Count > 0)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < compilerResults.Errors.Count; i++) { sb.Append(sb.Length > 0 ? “;” : “”);
sb.Append(compilerResults.Errors[i].ErrorText);
}
errorString = sb.ToString();
throw new Exception(“编译出错!” + sb.ToString());
}

Assembly assembly = compilerResults.CompiledAssembly;
Type type = assembly.GetType(“ExpressionCalculate”);
MethodInfo method = type.GetMethod(“Calculate”);
retvalue = method.Invoke(null, null);
}
catch (Exception ex)
{
logService.WriteLog(“编译出错,code=” + code, ex);
}
finally
{
csharpCodeProvider.Dispose();
}
return retvalue;
}

private string WrapExpression(string expression)
{
string code = @”
using System;

class ExpressionCalculate
{
public static object Calculate()
{
return {0};
}
}
“;
return code.Replace(“{0}”, expression);
}
其他方案:https://github.com/davideicardi/DynamicExpresso