c#中的线程问题
本文关键字:问题 线程 | 更新日期: 2023-09-27 18:05:53
我希望这个方法是线程化的,所以我可以设置一个计时器,而不是等待它完成。这是对服务的调用。
private static void callValueEng(ValueEngineService.Contracts.ValueEngServiceParams param)
{
using (WCFServiceChannelFactory<IValueEngineService> client =
new WCFServiceChannelFactory<IValueEngineService>(
Repository.Instance.GetWCFServiceUri(typeof(IValueEngineService))))
{
client.Call(x => x.ValueManyTransactionsWithOldEngines(translatedParams));
}
}
我试着像这样把它穿出来:
System.Threading.Thread newThread;
//RestartValueEngineService();
List<TransactionInfo> currentIdsForValuation = ((counter + 7000) <= allIds.Count)
? allIds.GetRange(counter, 7000)
: allIds.GetRange(counter, allIds.Count - counter);
translatedParams.tranquoteIds = currentIdsForValuation;
// thread this out
newThread = new System.Threading.Thread(callValueEng(translatedParams));
但是它说'最佳重载匹配有一些无效参数'。我做错了什么?
try:
var invoker = new Action<ValueEngineService.Contracts.ValueEngServiceParams>(callValueEng);
invoker.BeginInvoke(translatedParams, null, null);
System.Threading.Thread构造函数接受委托作为参数。试着
newThread = new System.Threading.Thread(new ParameterizedThreadStart(callValueEng));
newThread.start(translatedParams);
System.Threading.Thread类中没有构造函数接受你传递的委托类型。您只能传递threadstart或paramererizedthreadstart类型委托。
回答你的问题"我做错了什么?"-你试图传递带有ParameterizedThreadStart
委托不支持的签名的方法(见这里)
签名应该是
void ParameterizedThreadStart(Object obj)
而不是
void ParameterizedThreadStart(
ValueEngineService.Contracts.ValueEngServiceParams param)
您使用的是。net 4吗?如果是,你可以这样做:
Task.Factory.StartNew(() => callValueEng(translatedParams));
它会在一个新线程上运行你的代码。如果你需要在某事完成时做某事,那么你也可以很容易地做到:
Task.Factory.StartNew(() => callValueEng(translatedParams))
.ContinueWith(() => /* Some Other Code */);