C# 如何(有效地)在Windows窗体上执行多线程?
这件事让我很难过。 问题是我有一个在MIDI中播放一些音符的代码,我希望能够暂停它,所以我制作了一个简单的表单,如下所示:C# 如何(有效地)在Windows窗体上执行多线程?,c#,.net,winforms,multithreading,backgroundworker,C#,.net,Winforms,Multithreading,Backgroundworker,这件事让我很难过。 问题是我有一个在MIDI中播放一些音符的代码,我希望能够暂停它,所以我制作了一个简单的表单,如下所示: namespace Music { public partial class Form1 : Form { static BackgroundWorker _bw = new BackgroundWorker { WorkerSupportsCancellation = true };
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
}
}
}
当我点击它开始播放,但无论我做什么,它都不能停止。但问题是,如果我在控制台中做同样的事情,它会工作得很完美
我错过什么了吗?
如何控制窗体中的独立线程?这似乎可行
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);
}
}
}
}
CancelAsync()
方法只是将CancellationPending
属性设置为true
。这取决于工作线程来处理它(很可能是通过定期检查挂起的取消),因为它认为合适。成功了!是的,正如Ani所说,我正在将CancellationPending属性设置为true,但实际上我并没有取消。奇怪的是,在控制台中,它实际上起了作用。谢谢