【问题标题】:.NET threading returns value? [duplicate].NET 线程返回值? [复制]
【发布时间】:2011-07-05 03:34:18
【问题描述】:

可能重复:
Returning a value from thread?

我有这个代码:

//Asynchronously start the Thread to process the Execute command request.
Thread objThread = new Thread(new ParameterizedThreadStart(ExecuteCommandSync));
//Make the thread as background thread.
objThread.IsBackground = true;
//Set the Priority of the thread.
objThread.Priority = ThreadPriority.AboveNormal;
//Start the thread.
objThread.Start(command);

问题是ExecuteCommandSync返回一个字符串。

如何捕获返回的字符串并返回?

【问题讨论】:

  • 在类级别变量(字段)上分配字符串?
  • 您将需要一个 IAsyncResult 在线程之间共享数据。但就其本质而言,异步函数无法返回数据。我可以为您编写一个示例,以便在线程之间安全地共享数据。这个控制台是什么应用程序类型?赢表格? WPF?网络?

标签: c# .net multithreading return-value


【解决方案1】:

我建议您研究 .NET 4 中的 TPL。它允许您这样做:

Task<string> resultTask = Task.Factory.StartNew( () => ExecuteCommandSync(state) );

稍后,当您需要结果时,您可以通过以下方式访问它(如果方法未完成,则会阻塞):

string results = resultTask.Result;

【讨论】:

    【解决方案2】:

    如果回调返回一些东西,你不能使用ParameterizedThreadStart。请尝试以下操作:

    Thread objThread = new Thread(state => 
    {
        string result = ExecuteCommandSync(state);
        // TODO: do something with the returned result
    });
    //Make the thread as background thread.
    objThread.IsBackground = true;
    //Set the Priority of the thread.
    objThread.Priority = ThreadPriority.AboveNormal;
    //Start the thread.
    objThread.Start(command);
    

    还要注意objThread.Start 启动线程并立即返回。因此,请确保在线程完成执行之前托管进程不会结束,因为您将其设置为后台线程,它将被中止。否则不要让它成为后台线程。

    【讨论】:

      【解决方案3】:

      来自Threading in C# by Joseph Albahari

      你可以这样做:

      static int Work(string s) { return s.Length; }
      
      static void Main(string[] args)
      {
        Func<string, int> method = Work;
        IAsyncResult cookie = method.BeginInvoke ("test", null, null);
        //
        // ... here's where we can do other work in parallel...
        //
        int result = method.EndInvoke (cookie);
        Console.WriteLine ("String length is: " + result);
      

      【讨论】:

        【解决方案4】:

        你不能。

        线程在后台运行,并且仅在您的其余代码之后的一段时间内完成。

        【讨论】:

          猜你喜欢
          • 2016-01-09
          • 1970-01-01
          • 2013-11-06
          • 2012-02-27
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多