Home > Mobile >  How to get the result from a function in a separate thread c#
How to get the result from a function in a separate thread c#

Time:11-16

I have been trying to get a result from a function that is in a separate thread. For example:

public class Class1
{
    public static void DisplayResult()
    {
        MessageBox.Show(GetResult().ToString());
    }

   private static double GetResult()
   {
       double Result = 0;

        System.Threading.Thread thread = new System.Threading.Thread(() =>
        {
            for(int i = 0; i < 10000000; i  )
            {
               Result  = 1;
            }
        });
        thread.Start();

        return Result; 
  }
}

How can I make GetResult wait until the thread has ended before returning the result? Thanks.

CodePudding user response:

Here is an example to run a task in another thread:

using System;
using System.Threading.Tasks;

namespace ConsoleApp
{
    internal class Program
    {
        public static void Main()
        {
            var task = GetResultAsync();
            task.ContinueWith(x => {
                Console.WriteLine($"The task result is: {x.Result}");
                return Task.CompletedTask;
            });

            Console.WriteLine("Continue the UI thread...");
            Console.ReadKey();
        }

        private static async Task<double> GetResultAsync()
        {
            Console.WriteLine("Task thread begin.");

            double result = 0;
            await Task.Run(() =>
            {
                for (int i = 0; i < 10000000; i  )
                {
                    result  = 1;
                }
            });

            Console.WriteLine("Task thread end.");
            return result;
        }
    }
}


  • Related