如何在Windows窗体上多线程(有效)?

时间:2011-01-24 05:02:33

标签: c# .net winforms multithreading backgroundworker

这个让我很难过。 问题是我有一个代码在MIDI中播放一些音符,我希望能够暂停它,所以我做了一个简单的表格:

namespace Music
{
    public partial class Form1 : Form
    {

        static BackgroundWorker _bw = new BackgroundWorker
        {
            WorkerSupportsCancellation = true
        };

        private void button1_Click(object sender, EventArgs e)
        {
            if (!Playing)
            {
                Playing = true;
                _bw.DoWork += Start_Playing;
                _bw.RunWorkerAsync("Hello to worker");
            }
            else
            {
                Playing = false;
                _bw.CancelAsync();
            }
        }

        static void Start_Playing(object sender, DoWorkEventArgs e)
        {
            //Plays some music
        }
    }
}

当我点击它开始播放时,无论我做什么,它都无法停止。但问题是,如果我在控制台中做同样的事情,那就完美了。

我错过了什么吗? 如何从表单中控制单独的线程?

1 个答案:

答案 0 :(得分:3)

这似乎有用......

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        private BackgroundWorker _bw = new BackgroundWorker { WorkerSupportsCancellation = true, 
            WorkerReportsProgress = true};
        public Form1()
        {
            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (_bw.IsBusy)
            {
                _bw.CancelAsync();
            }
            else
            {
                _bw.ProgressChanged += new ProgressChangedEventHandler(_bw_ProgressChanged);
                _bw.DoWork += new DoWorkEventHandler(_bw_DoWork);
                _bw.RunWorkerAsync();
            }
        }

        void _bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            textBox1.Text += (string)e.UserState;
        }

        void _bw_DoWork(object sender, DoWorkEventArgs e)
        {
            int count = 0;
            while (!_bw.CancellationPending)
            {
                _bw.ReportProgress(0, string.Format("worker working {0}", count));
                ++count;
                Thread.Sleep(2000);
            }
        }
    }
}