0
votes

I need help: I've a nested object with associated Thread:

public class XNodeViewModel 
{
    private int id;
    private Thread workerThread;
    private bool _alivingThread;
    readonly ObservableCollection<XNodeViewModel> _children;

    private XNodeViewModel(...)
    {
        ...
        if (...)
        {
            workerThread = new Thread(DoWork) { IsBackground = true };
            workerThread.Start();
        }
    }
    public ObservableCollection<XNodeViewModel> Children
    {
        get { return _children; }
    }

    public int Level
    {
        get { return _xnode.Level; }
    }
    public Thread WorkerThread
    {
        get { return this.workerThread; }
    }
}

in wpf code behind i've a reference to this ViewModel and i want to get all threads obects associated. I'm learning Linq and i know that there are Function SelectMany to flatten nested objects: With a button i want to stop all threads with this function:

public void StopAllThread()
{
    //_firstGeneration is my root object
    var threads = _firstGeneration.SelectMany(x => x.WorkerThread).ToList();
    foreach( thread in threads){
        workerThread.Abort();
    }
}

But the compiler tell me:

Error 1 The type arguments for method 'System.Linq.Enumerable.SelectMany(System.Collections.Generic.IEnumerable, System.Func>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

Only if i request type "Thread".(if i'm requesting another type of object is ok) where am I doing wrong?

1
try using Select instead of SelectMany - Gopesh Sharma
Side note, you shouldn't use Abort in this case. Abort shall be used in exceptional situations. Consider using Join instead and have CancelationToken in place. - oleksii

1 Answers

2
votes

You need to use Select instead of SelectMany:

var threads = _firstGeneration.Select(x => x.WorkerThread);
foreach(thread in threads)
    workerThread.Abort();

SelectMany is used to flatten a list of lists. Your WorkerThread property doesn't return a list, so SelectMany is the wrong method.