Tuesday, January 31, 2017

Return a Value from function using thread

1. First Version

string res = null;
Thread newThread = new Thread(() => {res = sayHello("world!");}); 
newThread.Start(); 
newThread.Join(1000); 
Console.Writeline(res);

2. Second Version : Using Background Worker

In DoWork you can set e.Result =Value;

And in RunWorkerCompleted event you can get the result using e.Result.

DoWork event
private void BackgroundWorker1_DoWork(
    object sender,
    System.ComponentModel.DoWorkEventArgs e)
{
    AreaClass2 AreaObject2 = (AreaClass2)e.Argument;
    // Return the value through the Result property.
    e.Result = AreaObject2.CalcArea();
}

RunWorkerCompleted event
private void BackgroundWorker1_RunWorkerCompleted(
    object sender,
    System.ComponentModel.RunWorkerCompletedEventArgs e)
{
    // Access the result through the Result property.
    double Area = (double)e.Result;
    MessageBox.Show("The area is: " + Area.ToString());
}

3. Using Task class

.NET 4.0
Without specifying an input parameter:


Task task = new Task(() =>
{
int total = 0;
for (int i = 0; i < 500; i++)
{
total += i;
}
return total;
});

task.Start();
int result = Convert.ToInt32(task.Result);

.NET 4.5
The recommended way in .NET 4.5 is to use Task.FromResult, Task.Run or Task.Factory.StartNew:
FromResult:


public async Task DoWork()
{
int res = await Task.FromResult(GetSum(4, 5));
}

private int GetSum(int a, int b)
{
return a + b;
}

No comments:

Followers

Link