In this post, we will see how to return a value from a Thread.
First of all, we create a new Console application project where we define three methods called Method1, Method2 and Method3:
private static void Method1()
{
for(int i=1; i<5; i++)
{
Console.WriteLine($"Method1 {i}");
Thread.Sleep(2000);
}
}
private static void Method2()
{
for (int i = 6; i < 11; i++)
{
Console.WriteLine($"Method2 {i}");
Thread.Sleep(2000);
}
}
private static string Method3()
{
int result = 0;
for (int i = 1; i < 5; i++)
{
result += i;
Thread.Sleep(1000);
}
return $"The total is: {result}";
}
Then, we modify the Main method in order to run the first two methods in different Threads:
static void Main(string[] args)
{
Thread firstThread = new Thread(Method1);
Thread secondThread = new Thread(Method2);
firstThread.Start();
secondThread.Start();
}
If we run the application, this will be the result:
Now, we add another Thread where we will run the third method that will give us a string in output:
static void Main(string[] args)
{
Thread firstThread = new Thread(Method1);
Thread secondThread = new Thread(Method2);
// Definition of a variable used to store the output of Method3
string resultThread = string.Empty;
// Using a lambda expression for the definition of a new Thread
Thread thirdThread = new Thread(() => { resultThread = Method3(); });
firstThread.Start();
thirdThread.Start();
secondThread.Start();
// We need to use Join in order to take the parameter in output
thirdThread.Join();
Console.WriteLine($"The result of Method3 is: {resultThread}");
}
If we run the application, this will be the result:
Everything works fine but, we can see that the output of the third method is displayed in the middle of the application running.
If we want to see it at the end of all Threads, we have to use Join in the second method as well:
using System;
using System.Threading;
namespace MultiThreading
{
class Program
{
static void Main(string[] args)
{
Thread firstThread = new Thread(Method1);
Thread secondThread = new Thread(Method2);
// Definition of a variable used to store the output of Method3
string resultThread = string.Empty;
// Using a lambda expression for the definition of a new Thread
Thread thirdThread = new Thread(() => { resultThread = Method3(); });
firstThread.Start();
secondThread.Start();
thirdThread.Start();
secondThread.Join();
// We need to use Join in order to give the parameter in output
thirdThread.Join();
Console.WriteLine($"The result of Method3 is: {resultThread}");
}
private static void Method1()
{
for(int i=1; i<5; i++)
{
Console.WriteLine($"Method1 {i}");
Thread.Sleep(2000);
}
}
private static void Method2()
{
for (int i = 6; i < 11; i++)
{
Console.WriteLine($"Method2 {i}");
Thread.Sleep(2000);
}
}
private static string Method3()
{
int result = 0;
for (int i = 1; i < 5; i++)
{
result += i;
Thread.Sleep(1000);
}
return $"The total is: {result}";
}
}
}
If we run the application, this will be the result: