| |

VerySource

 Forgot password?
 Register
Search
View: 663|Reply: 2

A question about a thread delegate calling a method with parameters!

[Copy link]

2

Threads

3

Posts

4.00

Credits

Newbie

Rank: 1

Credits
4.00

 China

Post time: 2020-3-9 23:30:01
| Show all posts |Read mode
Look at the following code: The problem is that the thread delegate created in the following code calls the Work () method. If I want to call the WorkOne (string msg) method, what should I write? Thank you.
static void Main (string [] args)
{
Thread currentThread = Thread.CurrentThread;
Thread workThread = new Thread (new ThreadStart (Work));
workThread.Start ();
Ranch
}

static void Work ()
{
         Console.WriteLine ("Hello Work");
}

static void WorkOne (string msg)
{
         Console.WriteLine ("Hello {0}", msg)
}
Reply

Use magic Report

0

Threads

27

Posts

21.00

Credits

Newbie

Rank: 1

Credits
21.00

 China

Post time: 2020-6-4 10:00:01
| Show all posts
The positive solution upstairs, ThreadStart takes no parameters, so you can call string msg as a global variable.
Reply

Use magic Report

0

Threads

8

Posts

7.00

Credits

Newbie

Rank: 1

Credits
7.00

 India

Post time: 2020-6-18 09:30:01
| Show all posts
for(int i = 1; i <= 5; i++)
        {
            Thread t = new Thread(new ParameterizedThreadStart(Worker));

            // Start the thread, passing the number.
            //
            t.Start(i);
        }

private static void Worker(object num)
    {
        // Each worker thread begins by requesting the
        // semaphore.
        Console.WriteLine("Thread {0} begins "+
            "and waits for the semaphore.", num);
        _pool.WaitOne();

        // A padding interval to make the output more orderly.
        int padding = Interlocked.Add(ref _padding, 100);

        Console.WriteLine("Thread {0} enters the semaphore.", num);
        
        // The thread's "work" consists of sleeping for
        // about a second. Each thread "works" a little
        // longer, just to make the output more orderly.
        //
        Thread.Sleep(1000 + padding);

        Console.WriteLine("Thread {0} releases the semaphore.", num);
        Console.WriteLine("Thread {0} previous semaphore count: {1}",
            num, _pool.Release());
    }
Reply

Use magic Report

You have to log in before you can reply Login | Register

Points Rules

Contact us|Archive|Mobile|CopyRight © 2008-2023|verysource.com ( 京ICP备17048824号-1 )

Quick Reply To Top Return to the list