多线程方法

时间:2017-03-01 12:04:18

标签: c# multithreading

我使用TPL开发了以下代码,除了如何重启任务外,一切正常。目前,当我点击button1时,线程会在textBox1开始,类似于button3textBox2。当我点击button3button4时,两个帖子都会被取消。

现在,我想重新启动button1button3点击事件中的线程。我尝试了很多方法,但无法知道如何做到这一点。

以下是代码:

public partial class Form1 : Form
{
    CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
    CancellationToken token;
    CancellationTokenSource cancellationTokenSource1 = new CancellationTokenSource();
    CancellationToken token1;

    public Form1()
    {
        InitializeComponent();
        token = cancellationTokenSource.Token;
        token1 = cancellationTokenSource1.Token;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Task t = Task.Factory.StartNew(() =>
        {
            var run = true;
            while (run)
            {
                for (int i = 0; i < 100; i++)
                {
                    if (token.IsCancellationRequested)
                    {
                        run = false;
                        break;
                        //token.ThrowIfCancellationRequested();
                    }
                    // your code
                    System.Threading.Thread.Sleep(1000);
                    Action act = () => textBox1.Text = Convert.ToString(i);
                    textBox1.Invoke(act);
                }
            }
        });
    }

    private void button2_Click(object sender, EventArgs e)
    {
        cancellationTokenSource.Cancel();
    }

    private void button3_Click(object sender, EventArgs e)
    {
        Task t1 = Task.Factory.StartNew(() =>
        {
            var run = true;
            while (run)
            {
                for (int i = 0; i < 100; i++)
                {
                    if (token1.IsCancellationRequested)
                    {
                        run = false;
                        break;
                        //token1.ThrowIfCancellationRequested();
                    }
                    // your code
                    System.Threading.Thread.Sleep(1000);
                    Action act = () => textBox2.Text = Convert.ToString(i);
                    textBox2.Invoke(act);
                }
            }
        });
    }

    private void button4_Click(object sender, EventArgs e)
    {
        cancellationTokenSource1.Cancel();
    }
}

1 个答案:

答案 0 :(得分:0)

您需要使用信令同步线程,通常使用Event Wait Handles来实现,例如AutoResetEvent,ManualReset和CountdownEvent。您可以使用ManualReset实现此目的。

声明ManualResetEvent:

CancellationTokenSource cancellationTokenSource1 = new CancellationTokenSource();
        CancellationToken token1;
private ManualResetEvent mre = new ManualResetEvent(false);

在CancellationRequest上修改

if (token.IsCancellationRequested) {
   run = false;
   mre.WaitOne();
 //token.ThrowIfCancellationRequested();
}

OnStart / OnResume:mre.Set();