【问题标题】:C# pass function with return and parameter to ThreadC#将带有返回和参数的函数传递给线程
【发布时间】:2015-07-23 00:38:36
【问题描述】:

我创建了一个带有参数和返回值的函数。这是以下代码:

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;
    }

如何从线程内部的方法中获取返回值?

【问题讨论】:

  • 您可能必须通过回调。我会考虑看看像 TPL (Task<bool>) 和 async/await 这样的更高级别的东西来做到这一点。如果你真的是从 url 读取文件,HttpClient 上有异步方法。

标签: c# multithreading parameters lambda return


【解决方案1】:

您应该使用任务来获得结果。类似下面的东西

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; }
}

有关详细信息,请参阅此 MSDN 条目。

【讨论】:

    【解决方案2】:

    传递给线程的方法的签名是void method(Object),换句话说它不能返回任何东西。处理此问题的一种方法是允许线程和主代码访问同一变量,该变量可用于发出结果信号:

    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;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-10-05
      • 2015-08-29
      • 2021-11-12
      • 1970-01-01
      • 1970-01-01
      • 2017-05-25
      • 2016-11-28
      • 1970-01-01
      • 2023-03-14
      相关资源
      最近更新 更多