Hello,
I have a simple code (below) that is using VS2017 DTE interface to start Visual Studio IDE, open a file and navigate to a line number. When I use this code with VS2015 - everything works as expected. But VS2017 freezes while trying to open a file. The main window caption shows (Not Responding). The only way out is to terminate VS2017 process. If I add Thread.Sleep(500) between Start() and Open(), then everything starts working. Is there a deadlock in VS2017 code?
//==============================================================================
// Visual studio automation test
//==============================================================================
using System;
using System.Text;
using System.Threading;
using System.Runtime.InteropServices;
namespace VSAutoTest
{
class VSAuto
{
private dynamic m_dte = null;
private string m_strProgID;
public string ProgID
{
get
{
return m_strProgID;
}
}
public VSAuto(string i_strProgID)
{
m_strProgID = i_strProgID;
}
public void Start()
{
Type tDTE = Type.GetTypeFromProgID(m_strProgID);
if (tDTE == null)
throw new Exception(m_strProgID + " not registered");
m_dte = Activator.CreateInstance(tDTE);
if (m_dte == null)
throw new Exception(m_strProgID + " instantiation failure");
}
public void SetVisible(bool i_bVisible)
{
if (m_dte != null)
{
dynamic MainWindow = m_dte.MainWindow;
MainWindow.Visible = i_bVisible;
}
}
public dynamic OpenFile(string i_strName)
{
dynamic doc = null;
string strViewKind = "{00000000-0000-0000-0000-000000000000}"; // m_dte.vsViewKindPrimary;
if (m_dte != null)
{
dynamic win = null;
win = m_dte.OpenFile(strViewKind, i_strName);
if (win != null)
{
win.Visible = true;
doc = win.Document;
}
}
return doc;
}
public void GoToLine(dynamic i_doc, int i_nLine)
{
dynamic selection = i_doc.Selection();
selection.GotoLine(i_nLine);
}
public void Quit()
{
if (m_dte != null)
m_dte.Quit();
}
}
class Program
{
static void Main(string[] args)
{
VSAuto vs = null;
dynamic doc = null;
try
{
vs = new VSAuto("VisualStudio.DTE.15.0");
vs.Start();
//Thread.Sleep(500);
Console.WriteLine("{0} started", vs.ProgID);
vs.SetVisible(true);
if (args.Length >= 1)
{
doc = vs.OpenFile(args[0]);
}
if (doc != null && args.Length >= 2)
{
int nLine = Int32.Parse(args[1]);
vs.GoToLine(doc, nLine);
}
Console.ReadKey();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
if(vs != null)
vs.Quit();
}
}
}