Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Threads that return data in .NET

I'm writing a program where I typically start five threads. The threads return in a non-determinate order. Each thread is calling a method which returns a List.

I'm doing this:

var masterList = List<string>();    
foreach (var threadParam in threadParams)
{
    var expression = threadParam ;
    ThreadStart sub = () => MyMethod(expressions);
    var thread = new Thread(sub)
    {
        Name = expression
    };

    listThreads.Add(thread);
    thread.Start();
}

var abort = true;
while (abort) //Wait until all threads finish
{
    var count = 0;
    foreach (var list in listThreads)
    {
        if (!list.IsAlive)
        {
            count++;
        }
    }

    if (count == listThreads.Count)
    {
        abort = false;
    }
}

So here is the problem:

Each thread when it terminates returns a list I would like to append the masterList declared earlier.

How would one go about this?

Also I KNOW there must be a better way than below to wait for all threads to finish

var abort = true;
while (abort) //Wait until all threads finish
{
    var count = 0;
    foreach (var list in listThreads)
    {
        if (!list.IsAlive)
        {
            count++;
        }
    }

    if (count == listThreads.Count)
    {
        abort = false;
    }
}
like image 498
Matt Avatar asked Jul 31 '09 22:07

Matt


People also ask

Can a thread return a value C#?

Threads do not really have return values. However, if you create a delegate, you can invoke it asynchronously via the BeginInvoke method. This will execute the method on a thread pool thread. You can get any return value from such as call via EndInvoke .

Can a thread return a value?

A thread cannot return values directly. The start() method on a thread calls the run() method of the thread that executes our code in a new thread of execution. The run() method in turn may call a target function, if configured.

What is a .NET thread?

Net Threading. Thread in computer science means a sequence of execution instructions that can run independently , that is a single flow of execution in a process.

What are the different types of threads in C#?

There are two types of threads, foreground and background. Besides the main application thread, all threads created by calling a Thread class constructor are foreground threads. Background threads are the threads that are created and used from the ThreadPool, which is a pool of worker threads maintained by the runtime.


1 Answers

Use a WaitHandle


Here's an example:

using System;
using System.Threading;

class ThreadSleeper
{
    int seconds;
    AutoResetEvent napDone = new AutoResetEvent(false);

    private ThreadSleeper(int seconds)
    {
        this.seconds = seconds; 
    }

    public void Nap()
    {
        Console.WriteLine("Napping {0} seconds", seconds);
        Thread.Sleep(seconds * 1000);
        Console.WriteLine("{0} second nap finished", seconds);
        napDone.Set();
    }

    public static WaitHandle DoSleep(int seconds)
    {
        ThreadSleeper ts = new ThreadSleeper(seconds);
        Thread thread = new Thread(new ThreadStart(ts.Nap));
        thread.Start();
        return(ts.napDone);
    }
}

public class OperationsThreadsWaitingwithWaitHandle
{
    public static void Main()
    {
        WaitHandle[] waits = new WaitHandle[2];
        waits[0] = ThreadSleeper.DoSleep(8);
        waits[1] = ThreadSleeper.DoSleep(4);

        Console.WriteLine("Waiting for threads to finish");
        WaitHandle.WaitAll(waits);
        Console.WriteLine("Threads finished");
    }
}

Links to check out:

  • Threads:Waiting with WaitHandle
  • Jon Skeet's post
  • Difference between Barrier in C# 4.0 and WaitHandle in C# 3.0?
  • Novice C# threading: WaitHandles
  • WaitHandle Exceptions and Work Arounds
  • Multithreading with C#
  • WaitHandle, AutoResetEvent and ManualResetEvent Classes in VB.Net
like image 130
Andreas Grech Avatar answered Sep 22 '22 10:09

Andreas Grech