SE1986
SE1986

Reputation: 2750

Passing Parameters and Retrieving Return Results from thread

I am creating an application which does multiple searches (of different systems) and want to use threading so that these searches can be synchronised rather than sequential. I have some search methods as follows:

class Employee
{
    public DataTable EmployeeSearch_SystemA(object EmployeeID)
    {
        // search happening here
        Thread.Sleep(5000); //simulating a search 

        // we would return the actual results here
        return new DataTable();
    }

    public DataTable EmployeeSearch_SystemB(object EmployeeID)
    {
        Thread.Sleep(4000);
        return new DataTable();
    }

    public DataTable EmployeeSearch_SystemC(object EmployeeID)
    {
        Thread.Sleep(2000);
        return new DataTable();
    }

}

I can run these sequentially from my main method:

static void Main(string[] args)
{
    Employee e = new Employee();
    e.EmployeeSearch_SystemA("ABCDEFG");
    e.EmployeeSearch_SystemB("ABCDEFG");
    e.EmployeeSearch_SystemC("ABCDEFG");
}

But for the Search of system B, we need to wait for the search of system A to complete.

How can I use threading to do something like the following:

static void Main(string[] args)
{
    // create threads
    Thread thSystemA = new Thread(e.EmployeeSearch_SystemA);
    Thread thSystemB = new Thread(e.EmployeeSearch_SystemB);
    Thread thSystemC = new Thread(e.EmployeeSearch_SystemC);

    // run the three searches as individual threads
    thSystemA.Start("ABCDEFG");
    thSystemB.Start("ABCDEFG");
    thSystemC.Start("ABCDEFG");

    DataTable resultsSystemA = // get the datatable that EmployeeSearch_SystemA returns
   // etc...
}

It appears you can only assign a void method to a thread

Upvotes: 2

Views: 36

Answers (1)

nvoigt
nvoigt

Reputation: 77304

Parallelizing them should be quite easy...

static void Main(string[] args)
{
    DataTable resultsSystemA;
    DataTable resultsSystemB;
    DataTable resultsSystemC;

    Employee e = new Employee();    

    var a = Task.Run(() => { resultsSystemA = e.EmployeeSearch_SystemA(); });
    var b = Task.Run(() => { resultsSystemB = e.EmployeeSearch_SystemB(); });
    var c = Task.Run(() => { resultsSystemC = e.EmployeeSearch_SystemC(); });

    Task.WaitAll(a, b, c);

    // use the datatables.
}

... provided the three methods are actually threadsafe and independent of each other. The fact that they are all in the same class makes me kinda doubt it, but that's your job, to make sure they are actually able to act independent of each other.

Upvotes: 2

Related Questions