Does c# have an equivalent of the Java Runnable interface?
If not how could this be implemented or is it simply not needed?
thanks.
Does c# have an equivalent of the Java Runnable interface?
Yes, it's ThreadStart
class Runner
{
void SomeMethod()
{
Thread newThread = new Thread(new ThreadStart(Run));
newThread.Start();
}
public void Run()
{
Console.WriteLine("Running in a different thread.")
}
}
Would be equivalent to the following Java code
class Runner implements Runnable {
void someMethod() {
Thread newThread = new Thread( this );
newThread.start();
}
public void run() {
out.println("Running in a different thread.");
}
}
The closest to a high level task-oriented threading API would be a BackgroundWorker. As others have mentioned, .NET (and thus C#) use delegates for representing a callable method. Java doesn't have that concept (function pointers), and instead uses interfaces for callable objects.
Nope. C# handles threads differently to Java. 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)..
It's not needed - threads in C# take an instance of a ThreadStart
or ParameterizedThreadStart
delegate which are the runnable components of the thread to execute.
.Net uses the ThreadStart
and ParameterizedThreadStart
delegates to bootstrap Threads.
Delegates being first-class citizens in .Net, you can keep a reference around if you need to.
C#
uses the ThreadStart
delegate instead of Java's Runnable
style.
public class Foo
{
public void DoStuff()
{
while (true)
{
// do some stuff
}
}
};
public class Bar
{
public static int Main()
{
Foo foo = new Foo();
// create a ThreadStart delegate and pass in the method that will run
// (similar to run on Java's Runnable)
Thread thread = new Thread(new ThreadStart(foo.DoStuff));
thread.Start();
}
}