0

In a VS extension project, I am trying to create a mapping of the process threads, cast as both EnvDTE.Thread (to access the Freeze and Thaw methods), and System.Threading.Thread (to access the ManagedThreadId property).

It should ideally be as follow, but the cast will not compile, saying that it cannot cast from System.Threading.Thread to EnvDTE.Thread.

var threads = new Dictionary<EnvDTE.Thread, System.Threading.Thread>();
foreach (System.Threading.Thread thread in this.dte.Debugger.CurrentProgram.Threads) {
    threads.Add((EnvDTE.Thread)thread, thread);
}

How can I force the cast, knowing that it will not throw an exception (unless I am missing something here)?

Edit: it does throw an InvalidCastException.

Erwin Mayer
  • 18,076
  • 9
  • 88
  • 126

2 Answers2

1

have you tried casting back to an object first?

threads.Add((EnvDTE.Thread)(object)thread, thread);
Bob Vale
  • 18,094
  • 1
  • 42
  • 49
  • Just tried, but does not work (raises System.InvalidCastException at runtime)... However it still disabled the Compiler error. – Erwin Mayer Jul 07 '11 at 23:51
0

The compilation error you're getting is a bit of a red herring.

Debugger.CurrentProgram.Threads already returns a collection of EnvDTE.Thread objects, so your foreach will fail when attempting to cast them to System.Threading.Thread since there is no relation between those classes beyond the name.

EnvDTE.Thread has an ID property. Would that do what you want without needing to convert to a System.Threading.Thread?

Adam Lear
  • 38,111
  • 12
  • 81
  • 101
  • Alas, the ID property is not the ManagedThreadId, this is the only information that I miss from System.Threading.Thread. As for the casting to EnvDTE.Thread or System.Threading.Thread, both work if done in the loop variable declaration. Here, I am trying to avoid to iterate over the CurrentProgram.Threads object twice. – Erwin Mayer Jul 07 '11 at 23:43
  • 2
    @Erwin It looks like mapping an OS thread to a managed thread [is impossible](http://stackoverflow.com/questions/1749541/getting-from-processthread-to-a-managed-thread). – Adam Lear Jul 07 '11 at 23:52
  • Thanks Anna, indeed it seems impossible. It is even impossible to do a mapping with Process.GetCurrentProcess().Threads because there are no matching IDs. I'm out of luck for this time. – Erwin Mayer Jul 08 '11 at 00:00