使用Task在每个ListBox项上打开新线程

时间:2013-06-01 17:41:22

标签: c# winforms

这是我的播放按钮点击事件,我想从我的Listbox获取每个文件并执行操作:

    private void btnPlay_Click(object sender, EventArgs e)
    {
        MyClass calss = new MyClass();
        Task.Factory.StartNew(() =>
        {
            var files = listBoxFiles.Items.Count;
            Parallel.ForEach(files ,
                             new ParallelOptions
                             {
                                 MaxDegreeOfParallelism = 10 // limit number of parallel threads here 
                             },
                             file =>
                             {
                                 class.sendBuffer(file, selectedAdapter.PacketDevice, getSpeed(), capinfos.packets);
                             });
        }).ContinueWith(
                 t => { /* when all files processed. Update your UI here */ }
                 , TaskScheduler.FromCurrentSynchronizationContext() // to ContinueWith (update UI) from UI thread
             );
    }

我得到错误,我不知道如何解决Parallel.ForEach错误1无法从用法中推断出方法'System.Threading.Tasks.Parallel.ForEach(System.Collections.Generic.IEnumerable,System.Threading.Tasks.ParallelOptions,System.Action)'的类型参数。请尝试明确指定类型参数。

1 个答案:

答案 0 :(得分:1)

而不是

var files = listBoxFiles.Items.Count;

使用

var files = listBoxFiles.Items.Cast<String>().ToList();;

因为您需要遍历ListBox中的各个项目。

我假设你的列表框是一个字符串集合。