Search code examples
c#multithreadingwinformsadb

System.Threading.ThreadStateException OpenFileDialog


Today, I was trying to make an adb client in C# with a decent GUI. So, i 've done some research and found SharpAdbClient.

To do a file push, I use var file = openFileDialog2.ShowDialog(); to select a file. But if I try pushing a big file, the GUI stops responding (how it's supposed to be).

So, to solve this issue, I've set up a thread that does the push but I've got a ThreadStateException when I try to launch the OpenFileDialog.

Here's an example code:

private void button4_Click(object sender, EventArgs e)
{
    Thread pushFile = new Thread(push);
    pushFile.Start();
}

private void push()
{
    var device = AdbClient.Instance.GetDevices().First();
    var file = openFileDialog2.ShowDialog();
    var p = new Progress<int>(Progress_Bar);

    String newPath = textBox2.Text;
    if (file == DialogResult.OK)
    {
        String filePath = openFileDialog2.InitialDirectory + openFileDialog2.FileName;
        using (SyncService service = new SyncService(new AdbSocket(new IPEndPoint(IPAddress.Loopback, AdbClient.AdbServerPort)), device))
        using (Stream stream = File.OpenRead(filePath))
        {
            service.Push(stream, newPath, 444, DateTime.Now, p, CancellationToken.None);
        }
    }
}

Solution

  • You can't invoke UI-methods on threads that are not the GUI thread. You'll have to dispatch that to the correct thread. In WinForms, you'd use Invoke, BeginInvoke and similar to do that.

    Have a look at the Control.Invoke documentation for more information on this.