使用Linq </thread>选择<thread>对象

时间:2013-02-06 09:43:27

标签: c# wpf multithreading linq

我需要帮助: 我有一个带有关联线程的嵌套对象:

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; }
    }
}

在wpf代码后面我已经引用了这个ViewModel,我想让所有线程对象关联起来。 我正在学习Linq和我知道有函数SelectMany来展平嵌套对象: 使用按钮我想要使用此功能停止所有线程:

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

但是编译器告诉我:

错误1无法从用法推断出方法'System.Linq.Enumerable.SelectMany(System.Collections.Generic.IEnumerable,System.Func&gt;)'的类型参数。请尝试明确指定类型参数。

只有我请求输入“Thread”类型。(如果我要求其他类型的对象可以) 我在哪里做错了?

1 个答案:

答案 0 :(得分:2)

您需要使用Select代替SelectMany

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

SelectMany用于展平列表列表。您的WorkerThread属性不会返回列表,因此SelectMany是错误的方法。