Update UI inside backgroundworker in endless thread with C # and WinForms

1

I have an application made in Windows forms that is responsible for searching infinitely in a database for tasks to perform.

When I execute the code inside the Constructor of the form, it works but at moments it stops when launching new threads. The application consists of many threads that look for tasks, launch tasks, finish tasks and obtain updates from the database to maintain a "pool" of threads.

The problem I have is that when I try to move the Construct code to a BackgroundWoker, I can not update a text field that I have as an "output console". When trying to update my control txtConsoleOut this throws the following exception: "Cross-thread operation not valid: Control 'txtConsoleOut' accessed from a thread other than the thread it was created on."

I found how to update the UI using the RunWorkerCompleted method but it does not work because the application should never end the search loop.

Is there any way to update the control from a thread that did not start it? I leave my code for the part that throws the exception

Builder:

public frmAdminDespachador()
        {
            JsonConfig.rutaJson = "Despachador.json";
            InitializeComponent();
            InicializarCampos();
            backgroundWorker1.RunWorkerAsync();
        }

DoWork of the BackgroundWorker

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                //Thread.Sleep(10000);
                tConsola.Text = "";
                Log.Info("*********************************************************", APPNAME, tConsola);
                Log.Info("Iniciando aplicación", APPNAME, tConsola);
                Log.Info("*********************************************************", APPNAME, tConsola);
                //Mas código

Log.Info is an extension method of Log4Net

public static void Info(this ILog log, string cadena, string guid,TextBox textBox)
        {
            ThreadContext.Stacks["guid"].Clear();
            ThreadContext.Stacks["guid"].Push(guid);
            log.Info(cadena);
            textBox.AppendText(cadena + "\n");
        }

Thanks in advance

    
asked by Killbunny 05.07.2018 в 17:17
source

1 answer

2

I found the solution:

The solution was to make a BeginInvoke in the extension of the Log.

public static void Info(this ILog log, string cadena, string guid,TextBox textBox)
    {
        ThreadContext.Stacks["guid"].Clear();
        ThreadContext.Stacks["guid"].Push(guid);
        log.Info(cadena);
        //Esta fue la modificación:
        textBox.BeginInvoke(new Action(() => { textBox.AppendText(cadena + "\n"); }));
    }
    
answered by 05.07.2018 / 19:32
source