0

I am hosting a SignalR server on ASP.net website and from that, I want to open FolderBrowserDialog in a client WinForms App. Both server and client connect correctly and I even receive the message on client side, but when I try to open FolderBrowserDialog in a new thread, it just doesnt open it and does nothing after that.

This is the code to send a message from WebForms:

public void sendToSpecific(string name, string message, string to)
    {
        // Call the broadcastMessage method to update clients.
        Clients.Caller.broadcastMessage(name, message);
        Clients.Client(dic[to]).broadcastMessage(name, message);
    }

The Winforms code is:

    private string _selectedFolder;
    HubConnection hubConnection;
    IHubProxy hubProxy;

    public Form1()
    {
        InitializeComponent();
        hubConnection = new HubConnection("http://localhost:49335");
        hubProxy = hubConnection.CreateHubProxy("ChatHub");
        hubProxy.On<string, string>("broadcastMessage", (name, message) => checkMessage(message));
        hubConnection.Start().Wait();
        hubProxy.Invoke("Notify", "Console app", hubConnection.ConnectionId);
    }

    private void checkMessage(string message)
    {
        if (message == "Open")
        {
            var t = new Thread((ThreadStart)(() =>
            {
                FolderBrowserDialog fbd = new FolderBrowserDialog();
                fbd.RootFolder = System.Environment.SpecialFolder.MyComputer;
                fbd.ShowNewFolderButton = true;
                if (fbd.ShowDialog() == DialogResult.Cancel)
                    _selectedFolder = "Cancelled";
                else
                {
                    _selectedFolder = fbd.SelectedPath;
                }
            }));

            t.SetApartmentState(ApartmentState.STA);
            t.Start();
            t.Join();

            lstMessages.Items.Add(_selectedFolder);
            hubProxy.Invoke("Send", "Console app", _selectedFolder).Wait();
        }
    }

Can anyone please tell what I am doing wrong, I have set the [STAThread] before static void Main() also.

Hemant Sisodia
  • 488
  • 6
  • 23
  • https://learn.microsoft.com/en-us/dotnet/framework/winforms/controls/how-to-make-thread-safe-calls-to-windows-forms-controls – Lex Li Mar 30 '19 at 16:54
  • @LexLi Thanks for the reply, but getting the same error after using both examples too in the provided link. – Hemant Sisodia Apr 02 '19 at 09:42
  • @LexLi Making some changes in the second example "Use the Invoke method with a delegate" did the work for me, checking it, will upload the code soon. Thanks for this mate. – Hemant Sisodia Apr 02 '19 at 10:11

0 Answers0