C# Call a method in a new thread

后端 未结 6 1280
甜味超标
甜味超标 2020-12-13 04:08

I am looking for a way to call a method on a new thread (using C#).

For instance, I would like to call SecondFoo() on a new thread. However, I would the

相关标签:
6条回答
  • 2020-12-13 04:13

    Asynchronous version:

    private async Task DoAsync()
    {
        await Task.Run(async () =>
        {
            //Do something awaitable here
        });
    }
    
    0 讨论(0)
  • 2020-12-13 04:13

    As far as I understand you need mean terminate as Thread.Abort() right? In this case, you can just exit the Foo(). Or you can use Process to catch the thread.

    Thread myThread = new Thread(DoWork);
    
    myThread.Abort();
    
    myThread.Start(); 
    

    Process example:

    using System;
    using System.Diagnostics;
    using System.ComponentModel;
    using System.Threading;
    using Microsoft.VisualBasic;
    
    class PrintProcessClass
    {
    
        private Process myProcess = new Process();
        private int elapsedTime;
        private bool eventHandled;
    
        // Print a file with any known extension.
        public void PrintDoc(string fileName)
        {
    
            elapsedTime = 0;
            eventHandled = false;
    
            try
            {
                // Start a process to print a file and raise an event when done.
                myProcess.StartInfo.FileName = fileName;
                myProcess.StartInfo.Verb = "Print";
                myProcess.StartInfo.CreateNoWindow = true;
                myProcess.EnableRaisingEvents = true;
                myProcess.Exited += new EventHandler(myProcess_Exited);
                myProcess.Start();
    
            }
            catch (Exception ex)
            {
                Console.WriteLine("An error occurred trying to print \"{0}\":" + "\n" + ex.Message, fileName);
                return;
            }
    
            // Wait for Exited event, but not more than 30 seconds.
            const int SLEEP_AMOUNT = 100;
            while (!eventHandled)
            {
                elapsedTime += SLEEP_AMOUNT;
                if (elapsedTime > 30000)
                {
                    break;
                }
                Thread.Sleep(SLEEP_AMOUNT);
            }
        }
    
        // Handle Exited event and display process information.
        private void myProcess_Exited(object sender, System.EventArgs e)
        {
    
            eventHandled = true;
            Console.WriteLine("Exit time:    {0}\r\n" +
                "Exit code:    {1}\r\nElapsed time: {2}", myProcess.ExitTime, myProcess.ExitCode, elapsedTime);
        }
    
        public static void Main(string[] args)
        {
    
            // Verify that an argument has been entered.
            if (args.Length <= 0)
            {
                Console.WriteLine("Enter a file name.");
                return;
            }
    
            // Create the process and print the document.
            PrintProcessClass myPrintProcess = new PrintProcessClass();
            myPrintProcess.PrintDoc(args[0]);
        }
    }
    
    0 讨论(0)
  • 2020-12-13 04:18

    If you actually start a new thread, that thread will terminate when the method finishes:

    Thread thread = new Thread(SecondFoo);
    thread.Start();
    

    Now SecondFoo will be called in the new thread, and the thread will terminate when it completes.

    Did you actually mean that you wanted the thread to terminate when the method in the calling thread completes?

    EDIT: Note that starting a thread is a reasonably expensive operation. Do you definitely need a brand new thread rather than using a threadpool thread? Consider using ThreadPool.QueueUserWorkItem or (preferrably, if you're using .NET 4) TaskFactory.StartNew.

    0 讨论(0)
  • 2020-12-13 04:26

    Does it really have to be a thread, or can it be a task too?

    if so, the easiest way is:

    Task.Factory.StartNew(() => SecondFoo())
    
    0 讨论(0)
  • 2020-12-13 04:35

    Unless you have a special situation that requires a non thread-pool thread, just use a thread pool thread like this:

    Action secondFooAsync = new Action(SecondFoo);
    
    secondFooAsync.BeginInvoke(new AsyncCallback(result =>
          {
             (result.AsyncState as Action).EndInvoke(result); 
    
          }), secondFooAsync); 
    

    Gaurantees that EndInvoke is called to take care of the clean up for you.

    0 讨论(0)
  • 2020-12-13 04:39

    Once a thread is started, it is not necessary to retain a reference to the Thread object. The thread continues to execute until the thread procedure ends.

    new Thread(new ThreadStart(SecondFoo)).Start();
    
    0 讨论(0)
提交回复
热议问题