那么在 C# 中有几种方法可以实现这一点
我个人建议您尝试响应式扩展
http://msdn.microsoft.com/en-us/data/gg577609.aspx
您实际上可以执行以下操作:
https://stackoverflow.com/a/10804404/1268570
我为你创建了这个,虽然它不是线程安全的,但这真的很容易,但这将是一个很好的起点
以一种形式
var a = Observable.Start(() => Thread.Sleep(8000)).StartAsync(CancellationToken.None);
var b = Observable.Start(() => Thread.Sleep(15000)).StartAsync(CancellationToken.None);
var c = Observable.Start(() => Thread.Sleep(3000)).StartAsync(CancellationToken.None);
Manager.Add("a", a.ObserveOn(this).Subscribe(x => MessageBox.Show("a done")));
Manager.Add("b", b.ObserveOn(this).Subscribe(x => MessageBox.Show("b done")));
Manager.Add("c", c.ObserveOn(this).Subscribe(x => MessageBox.Show("c done")));
private void button1_Click(object sender, EventArgs e)
{
Manager.Cancel("b");
}
管理器实用程序
public static class Manager
{
private static IDictionary<string, IDisposable> runningOperations;
static Manager()
{
runningOperations = new Dictionary<string, IDisposable>();
}
public static void Add(string key, IDisposable runningOperation)
{
if (runningOperations.ContainsKey(key))
{
throw new ArgumentOutOfRangeException("key");
}
runningOperations.Add(key, runningOperation);
}
public static void Cancel(string key)
{
IDisposable value = null;
if (runningOperations.TryGetValue(key, out value))
{
value.Dispose();
runningOperations.Remove(key);
}
}