0

I have been working on a manager application for a Minecraft server, when I run my program, the console shows and disappears, if I run it manually, it runs without and problems. Batch file code:

java -Xmx1024M -jar craftbukkit-1.7.2-R0.3.jar -o false

My full code (MessageBoxes are in Polish, becouse im from Poland, but later i will add support for other languages):

using System;
using System.IO;
using System.Windows.Forms;
using System.Diagnostics;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public Process server;

        private Boolean runServer()
        {
            if (!File.Exists(textBox2.Text))
            {
                MessageBox.Show("Brak określonej ścieżki dostępu! (" + textBox2.Text + ")", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            Process process = new Process
            {
                StartInfo =
                {
                    FileName = textBox2.Text,
                    //Arguments = textBox3.Text,
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    CreateNoWindow = false,
                }
            };

            process.OutputDataReceived += new DataReceivedEventHandler(server_outputDataReceived);
            process.ErrorDataReceived += new DataReceivedEventHandler(server_outputDataReceived);
            server = process;

            if (process.Start())
                return true;
            else
            {
                MessageBox.Show("Nie można włączyć serwera!", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }

        private String ReadFile(String filename, int line)
        {
            StreamReader reader = new StreamReader(filename);

            for (int i = 0; i < line; i++)
            {
                reader.ReadLine();
            }

            return reader.ReadLine();
        }

        private void ReloadOPs()
        {
            if (!File.Exists(textBox1.Text))
            {
                MessageBox.Show("Sciezka dostępu do pliku z listą graczy posiadających OP nie istnieje! (" + textBox1.Text + ")", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                tabControl1.SelectedTab = tabPageOptions;
                textBox1.SelectAll();
                return;
            }

            String line = ReadFile(textBox1.Text, 0);
            comboBox1.Items.Clear();
            for (int i = 1; i < File.ReadAllLines(textBox1.Text).Length; i++)
            {
                if (!String.IsNullOrWhiteSpace(ReadFile(textBox1.Text, i)))
                {
                    comboBox1.Items.Add(line);
                    line = ReadFile(textBox1.Text, i);
                }
            }

            MessageBox.Show("Lista graczy z OP, została odświeżona.");
        }

        // OPs combobox (OPs)
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            groupBox1.Text = comboBox1.SelectedItem.ToString();
            groupBox1.Visible = true;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            textBox1.Text = Application.StartupPath.ToString() + @"\ops.txt";
            ReloadOPs();
        }

        // Reload OPs button (OPs)
        private void button1_Click(object sender, EventArgs e)
        {
            ReloadOPs();
        }


        // Save button (Options)
        private void button4_Click(object sender, EventArgs e)
        {

        }

        private void server_outputDataReceived(object sender, DataReceivedEventArgs e)
        {
            addConsoleMessage(e.Data.ToString(), true);
        }

        // Run server button (Menu)
        private void button5_Click(object sender, EventArgs e)
        {
            if (!runServer())
                return;

            server.BeginOutputReadLine();
            button6.Enabled = true;
        }

        // Stop server button (Menu)
        private void button6_Click(object sender, EventArgs e)
        {
            if(!server.HasExited)
                server.Kill();
            button6.Enabled = false;
        }

        private void addConsoleMessage(String message, Boolean refresh)
        {
            listBox1.Items.Add(message);
            if (refresh)
                listBox1.Refresh();
        }
    }
}

My problem is that program crashes becouse InvaildOperationException was unhandled (listBox1.Items.Add(message) in addConsoleMessage). External error information: Invalid operation between threads: the control 'listBox1' is accessed from a thread other than the thread it was created.

2
  • 1
    Set breakpoint and debug addConsoleMessage function and check what actually causing it to throw exception. Commented Apr 15, 2014 at 12:26
  • It throws InvalidOperationException becouse, (as it says) "Invalid operation between threads: the control 'listBox1' is accessed from a thread other than the thread it was created." Commented Apr 15, 2014 at 12:29

1 Answer 1

2

You cannot update UI form background thread. Try this

WPF

    private void server_outputDataReceived(object sender, DataReceivedEventArgs e)
    {
        Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Normal, () =>
                {
                     addConsoleMessage(e.Data.ToString(), true);
                });
    }

Update

In WinForms the Invoke/BeginInvoke methods are directly on the control objects as you can see from the docs of System.Windows.Forms.Control. So you'd have listBox1.BeginInvoke(...) for example.

Sign up to request clarification or add additional context in comments.

2 Comments

The type or namespace name 'Threading' does not exist in the namespace 'System.Windows' (are you missing an assembly reference?)
This appears to answer a question targeting WPF, but the OP is using WinForm public partial class Form1 : Form.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.