简体   繁体   English

具有线程返回和参数的C#传递函数

[英]C# pass function with return and parameter to Thread

I created a function with paramter and return value. 我创建了一个带有参数并返回值的函数。 This is the following code: 这是下面的代码:

static void Main(string[] args)
    {
        string url = "URL";

        Thread thread = new Thread(
            () => readFile(url)
            );
        thread.Start();
    }

    public static bool readFile(string url)
    {           
            bool result = true;
            return result;
    }

How can i get the return value from the method inside of thread? 我如何从线程内部的方法获取返回值?

The signature for the method passed to the thread is void method(Object) , in other words it can't return anything. 传递给线程的方法的签名为void method(Object) ,也就是说,它无法返回任何内容。 One way to handle this is to allow both the thread and the the main code access to the same variable, which can be used to signal the result: 一种解决方法是允许线程和主代码访问同一变量,该变量可用于表示结果:

class SomeClass
{
    private static bool threadResult;

    static void Main(string[] args)
    {
        string url = "URL";

        Thread thread = new Thread(() => readFile(url));
        thread.Start();
        ...
        // when thread completed, threadResult can be read
    }

    private static void readFile(string url)
    {           
        threadResult = true;
    }
}

You should use a task to get the result. 您应该使用任务来获得结果。 Something like below 像下面这样

class myClass
{
  static void Main(string[] args)
  {
   Task<ReadFileResult> task = Task<ReadFileResult>.Factory.StartNew(() =>
    {
       string url = "URL";
       return readFile(url));
    });
   ReadFileResult outcome = task.Result;
  }

  private static ReadFileResult readFile(string url)
  {           
    ReadFileResult r = new ReadFileResult();
    r.isSuccessFull = true;
    return r;
  }
}
class ReadFileResult
{
     public bool isSuccessFull { get; set; }
}

For more information see this MSDN entry. 有关更多信息,请参见此MSDN条目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM