3

有这样的代码。

启动线程:

Thread[] thr;
static object locker = new object();
bool liking = true;
private void button2_Click(object sender, EventArgs e)
{
    button2.Enabled = false;
    button3.Enabled = true;
    string post = create_note();

    decimal value = Program.Data.numericUpDown1;
    int i = 0;
    int j = (int)(value);
    thr = new Thread[j];
    for (; i < j; i++)
    {
        thr[i] = new Thread(() => invite(post)); 
        thr[i].IsBackground = true;
        thr[i].Start();
    }

}
public void invite(string post)
{
    while (liking)
    {
        if (//some comdition)
            exit all threads, and start string post = create_note(); again
    }
}

如果某些条件invite(string post)成立,我需要停止所有线程,然后string post = create_note();再次转到,获取字符串发布并再次启动线程。

怎么做?

4

2 回答 2

3

Parallel.For使用with代替手动线程管理CancellationToken

        var cts = new CancellationTokenSource();
        var options = new ParallelOptions 
        { 
            CancellationToken = cts.Token,
            MaxDegreeOfParallelism = System.Environment.ProcessorCount
        };
        var result = Parallel.For(0, j, options, i =>
        {
            invite(post);
            options.CancellationToken.ThrowIfCancellationRequested();
        });

当您想取消并行计算时,只需cts.Cancel()从外部代码调用。

于 2013-07-28T10:55:29.667 回答
0

您可以使用 lock 并创建一个类来管理您的线程,如下所示:

public class SyncClass
{
    public Thread[] thr;
    private int NumberOfWorkingThreads { get; set; }
    private object Sync = new object();

    public int ThreadNumber { get; private set; }

    public event EventHandler TasksFinished;

    public SyncClass(int threadNumber)
    {
        thr = new Thread[threadNumber];
        ThreadNumber = threadNumber;
        NumberOfWorkingThreads = ThreadNumber;
        //LunchThreads(threadNumber);
    }

    protected void OnTasksFinished()
    {
        if (TasksFinished == null)
            return;
        lock (Sync)
        {
            NumberOfWorkingThreads--;
            if (NumberOfWorkingThreads == 0)
                TasksFinished(this, new EventArgs());
        }
    }

    public void LunchThreads()
    {
        string post = create_note();
        for (int i = 0; i < ThreadNumber; i++)
        {
            thr[i] = new Thread(() => invite(post));
            thr[i].IsBackground = true;                
            thr[i].Start();
        }
    }

    private void invite(string post)
    {
        while (true)
        {
            if (true)
            {
                break;
            }
        }
        OnTasksFinished();
    }


}

使用该事件来通知所有线程的结束,然后该类将像这样使用:

    private void Operation()
    {
        var sync = new SyncClass(10);
        sync.TasksFinished += sync_TasksFinished;
        sync.LunchThreads();
    }



     void sync_TasksFinished(object sender, EventArgs e)
    {
        Operation();
    }
于 2013-07-28T11:19:37.383 回答