如何防止执行超出必要的任务

时间:2017-10-08 11:55:51

标签: c# multithreading task

我有一个多行文本框,我想用多线程处理每一行。这只是学习任务的一个例子,但我之后会用线条做不同的任务,而不仅仅是打印它们。

例如,假设我的文本框包含:

1
2
3
4
5
6
7
8
9
10

使用以下代码:

    List<Task> tasks = new List<Task>();

    for (int i = 0; i < txtSearchTerms.Text.Length; i++)
    {
        int tmp = i;
        Task t = new Task(() =>
                        {
                            Console.WriteLine(txtSearchTerms.Text[tmp]);
                        });
        tasks.Add(t);
        t.Start();
    }

    Task.WaitAll(tasks.ToArray());

    foreach(Task t in tasks)
    {
        Console.WriteLine("Task {0}, Status {1}", t.Id, t.Status);
    }

我得到以下输出:

1




3




4




5




6




7




8




9




1
0
2
Task 1, Status RanToCompletion
Task 2, Status RanToCompletion
Task 3, Status RanToCompletion
Task 4, Status RanToCompletion
Task 5, Status RanToCompletion
Task 6, Status RanToCompletion
Task 7, Status RanToCompletion
Task 8, Status RanToCompletion
Task 9, Status RanToCompletion
Task 10, Status RanToCompletion
Task 11, Status RanToCompletion
Task 12, Status RanToCompletion
Task 13, Status RanToCompletion
Task 14, Status RanToCompletion
Task 15, Status RanToCompletion
Task 16, Status RanToCompletion
Task 17, Status RanToCompletion
Task 18, Status RanToCompletion
Task 19, Status RanToCompletion
Task 20, Status RanToCompletion
Task 21, Status RanToCompletion
Task 22, Status RanToCompletion
Task 23, Status RanToCompletion
Task 24, Status RanToCompletion
Task 25, Status RanToCompletion
Task 26, Status RanToCompletion
Task 27, Status RanToCompletion
Task 28, Status RanToCompletion
Task 29, Status RanToCompletion

这么多“空间”的原因是什么,以及无缘无故地运行额外的任务以及如何防止它?

感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

您的代码存在问题,即您使用的是txtSearchTerms.Text而不是txtSearchTerms.Lines

根据https://stackoverflow.com/a/46630470/34092考虑​​使用:

var data = txtSearchTerms.Lines;
var threadCount = 4; // or whatever you want

Parallel.ForEach(data, 
    new ParallelOptions() { MaxDegreeOfParallelism = threadCount },
    (val) =>
    {
        //Your code here
        Console.WriteLine(val);
    });

或:

var data = txtSearchTerms.Lines;
var threadCount = 4; // or whatever you want

var results = data.AsParallel(new ParallelLinqOptions()
{
    MaxDegreeOfParallelism = threadCount
}).Select(val =>
{
    // Your code here, I just return the value but you could return whatever you want
    return val;
}).ToList();

答案 1 :(得分:-1)

我认为你有一个任务同步问题。代码似乎不以任何方式控制任务。当我改变时,任务可能会运行。 也许.run会更好地执行任务吗? 您的目标是否同步运行任务? https://msdn.microsoft.com/en-us/library/dd321435(v=vs.110).aspx

此stackoverflow线程可能很有用:Regarding usage of Task.Start() , Task.Run() and Task.Factory.StartNew()