2

I've started to play with c# interactive. In Visual Studio I was able to create some window with following code:

#r "PresentationFramework"
using System.Windows;
var w = new Window();
w.Show();

However due to this error using csi.exe I had to do something like this to see a window (I've run executable from net.compiler nuget package, tools directory):

#r "PresentationFramework"
using System.Windows;
using System.Threading;
var t = new Thread(()=>{var w = new Window(); w.Show(); Thread.Sleep(2000);});
t.SetApartmentState(ApartmentState.STA);
t.Start();

The window is displayed while the thread is running but I'm not sure how I could achieve behavior similar to this inside VS C# interactive view.

1 Answers1

1

[Edited]

Hi Paweł,

Here is an answer (tested in csi this time), based on: Launching a WPF Window in a Separate Thread

#r "PresentationFramework"
#r "Microsoft.VisualStudio.Threading"

using System.Windows.Controls;
using System.Windows;
using System.Threading;

var newWindowThread = new Thread(new ThreadStart(() =>
{
    var tempWindow = new Window();
    var t = new TextBox() {Text = "test"};
    tempWindow.Content = t;
    tempWindow.Show();
    System.Windows.Threading.Dispatcher.Run();
}));


newWindowThread.SetApartmentState(ApartmentState.STA);
newWindowThread.IsBackground = true;
newWindowThread.Start();
Maciek Świszczowski
  • 1,155
  • 11
  • 28
  • Thanks for answer but in *VS* everything is as I expect. I want to get the same behavior when using *csi.exe* in console. In *csi* the first piece of code does not work but the same code works in *VS* – Paweł Audionysos May 22 '18 at 15:12
  • By the way, a better title for this question would be 'WPF in csi.exe' – Maciek Świszczowski May 27 '18 at 10:53
  • Thank you for the answer but the may problem stays the same - I can't directly call window created in another thread even if I declare window variable outside created thread If I want to modify it I have to write something like this: `win.Dispatcher.Invoke(()=>{win.WindowState = WindowState.Maximized;});` And I thought `csi` stands for **C** **S**harp **I**nteractive and VS has only a view of it. Is't it? – Paweł Audionysos May 28 '18 at 17:58
  • Obviously csi and C# Interactive differ in the main thread type. In csi it's MTA, and C# Interactive it's STA. It should be possible to execute the above script and switch context to the new STA thread, though. – Maciek Świszczowski May 29 '18 at 06:42