Csharp/C#教程:预期C#方法名称分享


预期C#方法名称

我只是试图传递一些值,但它总是抛出一个错误。 有人可以纠正我在这里缺少的东西吗?

我在这里得到错误

Thread t_PerthOut = new Thread(new ThreadStart(ReadCentralOutQueue("test")); 

我想将此字符串值传递给ReadCentralOutQueue

 class Program { public void Main(string[] args) { Thread t_PerthOut = new Thread(new ThreadStart(ReadCentralOutQueue("test")); t_PerthOut.Start(); } public void ReadCentralOutQueue(string strQueueName) { System.Messaging.MessageQueue mq; System.Messaging.Message mes; string m; while (true) { try { } else { Console.WriteLine("Waiting for " + strQueueName + " Queue....."); } } } catch { m = "Exception Occured."; Console.WriteLine(m); } finally { //Console.ReadLine(); } } } } 

这段代码:

 Thread t_PerthOut = new Thread(new ThreadStart(ReadCentralOutQueue("test")); 

尝试调用ReadCentralOutQueue然后从结果中创建委托。 这不会起作用,因为它是一种无效方法。 通常,您将使用方法组来创建委托,或使用匿名函数 (如lambda表达式)。 在这种情况下,lambda表达式将是最简单的:

 Thread t_PerthOut = new Thread(() => ReadCentralOutQueue("test")); 

您不能只使用new Thread(ReadCentralOutQueue)因为ReadCentralOutQueueThreadStartParameterizedThreadStart的签名不匹配。

重要的是,您要了解为什么会收到此错误,以及如何解决此错误。

编辑:只是为了certificate它确实有效,这是一个简短但完整的程序:

 using System; using System.Threading; class Program { public static void Main(string[] args) { Thread thread = new Thread(() => ReadCentralOutQueue("test")); thread.Start(); thread.Join(); } public static void ReadCentralOutQueue(string queueName) { Console.WriteLine("I would read queue {0} here", queueName); } } 

不允许参数作为ThreadStart委托的一部分。 将参数传递给新线程还有其他几种解决方案,如下所述: http : //www.yoda.arachsys.com/csharp/threads/parameters.shtml

但在你的情况下可能最简单的是匿名方法:

 ThreadStart starter = delegate { Fetch (myUrl); }; new Thread(starter).Start(); 

你必须这样做:

 var thread = new Thread(ReadCentralOutQueue); thread.Start("test"); 

ParameterizedThreadStart还需要一个以object作为参数的委托,因此您需要将签名更改为:

上述就是C#学习教程:预期C#方法名称分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 public static void ReadCentralOutQueue(object state) { var queueName = state as string; ... } 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1027250.html

(0)
上一篇 2022年1月9日
下一篇 2022年1月9日

精彩推荐