How to call the method in thread with arguments and return some value

前端 未结 7 1812
南旧
南旧 2020-12-09 00:14

I like to call the method in thread with arguments and return some value here example

class Program
{
    static void Main()
    {
        Thread FirstThread         


        
相关标签:
7条回答
  • 2020-12-09 00:59

    You can use the ParameterizedThreadStart overload on the Thread constructor. It allows you to pass an Object as a parameter to your thread method. It's going to be a single Object parameter, so I usually create a parameter class for such threads.. This object can also store the result of the thread execution, that you can read after the thread has ended.

    Don't forget that accessing this object while the thread is running is possible, but is not "thread safe". You know the drill :)

    Here's an example:

    void Main()
    {
        var thread = new Thread(Fun);
        var obj = new ThreadObject
        {
            i = 1,
            j = 15,
        };
    
        thread.Start(obj);
        thread.Join();
        Console.WriteLine(obj.result);
    }
    
    public static void Fun(Object obj)
    {
        var threadObj = obj as ThreadObject;
        threadObj.result = threadObj.i + threadObj.j;
    }
    
    public class ThreadObject
    {
        public int i;
        public int j;
        public int result;
    }
    
    0 讨论(0)
提交回复
热议问题