private void button1_Click(object sender, EventArgs e) { if (button1.Text.Equals("插入数据")) { tokenSource = new CancellationTokenSource(); token = tokenSource.Token; button1.Text = "停止插入"; ThreadPool.QueueUserWorkItem(p => { List <Task> tasks = new List <Task>(); TaskFactory factory = new TaskFactory(); for (int i = 0; i < 5; i++) { Task task = factory.StartNew(() => { while (true) { token.ThrowIfCancellationRequested(); Student stu = new Student() { Name = Names[new Random().Next() % Names.Count()] + Names[new Random().Next(DateTime.Now.Millisecond) % Names.Count()], Age = new Random().Next() % 100 }; try { SqlHelper.Insert <Student>(stu, typeof(Student).Name); IndexHelper.CreateInstance().InsertIndex(stu); } catch (Exception exception) { log.Error("Error:", exception); } } }); tasks.Add(task); } try { Task.WaitAll(tasks.ToArray(), token); } catch { } }); } else { button1.Text = "插入数据"; tokenSource.Cancel(); IndexHelper.CreateInstance().MergeIndex(); } }
public static IndexHelper CreateInstance() { Object obj = new Object(); lock (obj) { if (instance == null) { lock (obj) { instance = new IndexHelper(); } } } return(instance); }