线程查杀名称

时间:2015-05-26 09:59:54

标签: c# wpf multithreading dispatcher

我的帖子有问题......

Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate {}));
Thread.Sleep(90);

它开始并且工作正常,但永远都是如此,我不想永远地运行这个主题。 有没有办法给这个线程一个名字,所以我可以在任何我想要的时候按名称杀死它? 我试着杀了它:

Dispatcher.CurrentDispatcher.thread.Abort();

但它杀死了整个应用...... 基本上... 我在我的WPF应用程序中有一个自定义组合...这个线程在while循环中,当我打开组合时开始循环(!context.IsClosed)但是当它关​​闭时,它仍然在后台运行

1 个答案:

答案 0 :(得分:3)

您对多线程方法的理解是完全错误的。

首先,不,没有办法以这种方式为你的线程命名 其次,在这种情况下杀死一个线程是一种完全错误的方法,有很简单的方法可以做这些事情:CancellationToken。您可以使用一些overloads for the Dispatcher.Invoke(使用或不使用启动超时),如下所示:

Dispatcher.Invoke Method (Action, DispatcherPriority, CancellationToken)

CancellationTokenSource s = new CancellationTokenSource();
Dispatcher.CurrentDispatcher.Invoke(() => YourMethodHere(), DispatcherPriority.Background, s.Token);
Thread.Sleep(90);

s.Cancel();

在调用Cancel方法后,.NET将自动停止你的线程。

第二种可能的方法,就是在评论中写的,就是使用TPL,而不使用Thread创建,类似这样的内容(来自MSDN article about SynchronizationContext的代码):

  // This TaskScheduler captures SynchronizationContext.Current.
  TaskScheduler taskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
  // Start a new task (this uses the default TaskScheduler, 
  // so it will run on a ThreadPool thread).
  Task.Factory.StartNew(() =>
  {
    // We are running on a ThreadPool thread here.
    // Do some work.
    // Report progress to the UI.
     Task reportProgressTask = Task.Factory.StartNew(() =>
       {
         // We are running on the UI thread here.
         // Update the UI with our progress.
       }, 
      s.Token, 
      TaskCreationOptions.None,
      taskScheduler);
    reportProgressTask.Wait();

    // Do more work.
  });