-1

I'm trying to save a file using saveFileDialog in F#. So far I've looked at this post and tried to rewrite that and other code on the net. I've also read a bit about saveFileDialogs on msdn.

I Think that my code should work but for some reason it crashes (if I press continue in the IDE I can even get a glimpse of the saveFileDialog but with wrong type-filter).

My crash message is "An exception of type 'System.Threading.ThreadStateException' occurred in System.Windows.Forms.dll but was not handled in user code"

and my code is:

let savefile = new SaveFileDialog()
    savefile.FileName <- "My Sudoku.txt"
    savefile.Filter <- "Text files (*.txt)|*.txt|All files (*.*)|*.*";
    savefile.InitialDirectory <- Directory.GetCurrentDirectory ()
    savefile.FilterIndex <- 1 

if savefile.ShowDialog(new Form(Text="Save", TopMost=true, Width=360, Height=390)) = System.Windows.Forms.DialogResult.OK 
                                         then saveFile    (savefile.InitialDirectory) (savefile.FileName) (stuffToSave)
                                         else printfn "Error couldn't save" 

The code is actually happening in a form named createMode which is started with async.

Async.Start(createMode observables sudokuGame) ; GUI.Create.form.ShowDialog() 
Community
  • 1
  • 1
  • 3
    Trying to do anything with WinForms controls on any thread other than the main thread is destined to failure. – ildjarn Jun 01 '15 at 09:38
  • 3
    I would try [`Async.SwitchToContext`](https://msdn.microsoft.com/en-us/library/vstudio/ee353903(v=vs.120).aspx) - if you look at the link you will have an WinForms example right there ... – Random Dev Jun 01 '15 at 13:22

1 Answers1

1

A way to fix this that I now have discovered is to add open System to the program. And to add

[<STAThreadAttribute>]
    do

before the async.Start part that starts the thread with the program.

  • 1
    I don't think that this will solve *all* your issue when you really end up in another thread ([see this for an explanation on this attribute](https://stackoverflow.com/questions/1361033/what-does-stathread-do)) – Random Dev Jun 01 '15 at 13:25