Threading: does c# have an equivalent of the Java Runnable interface?

前端 未结 7 1104
礼貌的吻别
礼貌的吻别 2021-01-31 15:44

Does c# have an equivalent of the Java Runnable interface?

If not how could this be implemented or is it simply not needed?

thanks.

相关标签:
7条回答
  • 2021-01-31 16:05

    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.");
          }
      }
    
    0 讨论(0)
  • 2021-01-31 16:06

    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.

    0 讨论(0)
  • 2021-01-31 16:14

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

    0 讨论(0)
  • 2021-01-31 16:15

    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.

    0 讨论(0)
  • 2021-01-31 16:16

    .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.

    0 讨论(0)
  • 2021-01-31 16:19

    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();
        }
    }
    
    0 讨论(0)
提交回复
热议问题