【问题标题】:Issues with threading in c#c#中的线程问题
【发布时间】:2011-08-18 13:51:13
【问题描述】:

我希望这个方法被线程化,这样我就可以设置一个计时器而不是等待它完成。这是对服务的调用。

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));

但它是说“最好的重载匹配有一些无效的参数。”我做错了什么?

【问题讨论】:

    标签: c# .net multithreading wcf


    【解决方案1】:

    尝试:

    var invoker = new Action<ValueEngineService.Contracts.ValueEngServiceParams>(callValueEng);
    invoker.BeginInvoke(translatedParams, null, null);
    

    这将异步调用您的方法。

    【讨论】:

    • 如何传递参数?
    • 修好了,出错了(忽略了参数)
    • 我们所需要的只是异步,所以无论如何它都能解决。谢谢:)
    • 请记住,您需要在 BeginInvoke 时调用 EndInvoke,否则您可能会引入泄漏。
    • @slandau :通过这种方式,您的应用程序可以处理,因为 BeginInvoke 将 pupm UI 线程消息池...我建议无论如何在专用线程中运行 thsi 代码
    【解决方案2】:

    System.Threading.Thread 构造函数将委托作为其参数。 试试

    newThread = new System.Threading.Thread(new ParameterizedThreadStart(callValueEng));
    newThread.start(translatedParams);
    

    【讨论】:

    • 这行不通,因为我猜我的方法格式不正确。
    • 问题是你的方法是静态的。线程构造函数采用一个委托,该委托映射到具有签名 void 方法(obj 参数)的方法。由于它是静态的,请使用发布的调用者答案。
    • @tafoo85 : 您可以将具有正确签名的静态方法传递给 Thread.Start(...),问题是 OP 的方法签名错误
    【解决方案3】:

    System.Threading.Thread 类中没有构造函数,它接受您传递的类型的委托。您只能传递 threadstart 或 paramererizedthreadstart 类型委托。

    【讨论】:

      【解决方案4】:

      回答您的问题“我做错了什么?” - 您试图传递带有 ParameterizedThreadStart 委托 (see here) 不支持的签名的方法

      签名应该是

       void ParameterizedThreadStart(Object obj)
      

      而不是

      void ParameterizedThreadStart(
                          ValueEngineService.Contracts.ValueEngServiceParams param) 
      

      【讨论】:

        【解决方案5】:

        您使用的是 .NET 4 吗?如果是这样,您可以这样做:

         Task.Factory.StartNew(() => callValueEng(translatedParams));
        

        它会在一个新线程上运行你的代码。如果您需要在完成后做某事,那么您也可以轻松做到:

        Task.Factory.StartNew(() => callValueEng(translatedParams))
            .ContinueWith(() => /* Some Other Code */);
        

        【讨论】:

          猜你喜欢
          • 2012-06-01
          • 2022-01-08
          • 2011-09-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多