user979033
user979033

Reputation: 6460

How to start Thread with lambda expression c#

I have this class:

public class Statistics
{
    List<string> _lsit;

    public List<string> ipList
    {
        get { return _lsit; }
        set { _lsit = value; }
    }

    string _Path = @"C:\Program Files\myApp.exe";
    string _Path = "";
    ProcessStartInfo ps = null;

    public getStatistics(string Path)
    {
        _Path = Path;
        getStatistics();
    }
}

I want to start the function Statistics with different Thead and i did somthing like:

Statistics stat = new Statistics (some path);
Thread<List<string>> lList = new Thread<List<string>>(() => tsharkIps.getStatistics());

but the compiler Error says "The non-generic type 'System.Threading.Thread' cannot be used with type arguments"

I did not write all my class and only want to know hot to start the thread

thanks

Upvotes: 11

Views: 30424

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500825

You need to take a step back to start with and read the compiler error. Thread is not a generic type. It's really not at all clear what you're trying to do here, especially as you haven't even shown a parameterless getStatistics() method (which should be called GetStatistics() to follow .NET naming conventions) and the parameterized getStatistics() method you have shown doesn't have a return type.

Starting a thread with a lambda expression is the easy part:

Thread thread = new Thread(() => CallSomeMethodHere());
thread.Start();

It's not clear how that translates to your sample code though.

Or using the TPL in .NET 4, you can (and probably should use Task or Task<T>):

Task task = Task.Factory.StartNew(() => CallSomeMethodHere());

or

Task<string> task = Task.Factory.StartNew(() => CallSomeMethodReturningString());

It's possible that you really want:

Task<List<string>> statisticsTask = Task.Factory.StartNew(() => {
   Statistics statistics = new Statistics(path);
   return statistics.ipList();
});

Note that here the constructor is called within the new task - which is important, as it looks like that's probably doing all the work. (That's usually a bad idea to start with, but that's another matter.)

You should look at .NET naming conventions in general, btw...

Upvotes: 35

Related Questions