C# version of Java Runnable? (delegate?)

时间秒杀一切 提交于 2019-12-13 15:24:33

问题


I could not find a direct answer to this question yet in SO. Is there a predefined delegate with void (void) signature?


回答1:


Action has the signature you're looking for. However, it doesn't mean the same thing as Runnable does: Runnable generally indicates that the run() method is intended to be run on a Thread, while Action makes no indication. For that you'd want ThreadStart, which has the same signature, and does make that indication.

If all you need is a delegate with no parameters, Action is what you want. If you're dealing with threads and need to indicate the start method, use ThreadStart.




回答2:


Nope. C# handles threads differently to Java. In Java, the Runnable interface is an alternative to subclassing Thread, but you still have to create a new Thread object, passing the Runnable to a constructor.

Rather than subclassing the Thread class, you simply create a new System.Threading.Thread object and pass it a ThreadStart delegate (this is the function where you do the work). ThreadStart is the exact C# equivalent to Java's Runnable.

However, the Action delegate has the void parameters you speak of.




回答3:


The Action delegate is a void with no parameters.

http://msdn.microsoft.com/en-us/library/system.action.aspx

There are also other signatures with up to 16 parameters.



来源:https://stackoverflow.com/questions/7078736/c-sharp-version-of-java-runnable-delegate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!