General issues

I'm crazy about simple [WPF C #] code in which I use BackgroundWorker to automate basic operations. Should I add content to the clipboard.

After executing this code in the BackgroundWorker method:

Clipboard.SetText (splitpermutation [i]);

I get an error message that explains that the stream must be STA, but I do not understand how to do this. Here is more code: (not all)

private readonly BackgroundWorker worker = new BackgroundWorker();

private void btnAvvia_Click(object sender, RoutedEventArgs e)
{
            count = lstview.Items.Count;
            startY = Convert.ToInt32(txtY.Text);
            startX = Convert.ToInt32(txtX.Text);
            finalY = Convert.ToInt32(txtFinalPositionY.Text);
            finalX = Convert.ToInt32(txtFinalPositionX.Text);
            incremento = Convert.ToInt32(txtIncremento.Text);
            pausa = Convert.ToInt32(txtPausa.Text);

            worker.WorkerSupportsCancellation = true;
            worker.RunWorkerAsync();

            ...
}

private void WorkFunction(object sender, DoWorkEventArgs e)
{
   [...]
                    if (worker.CancellationPending)
                    {
                        e.Cancel = true;
                        break;
                    }
                    else
                    {
                        [...]
                        Clipboard.SetText(splitpermutation[i]);
                        [...]
                    }
}
+5
source share
3 answers

You can do this for the user interface thread to make it work:

else
{
    [...]
    this.Dispatcher.BeginInvoke(new Action(() => Clipboard.SetText(splitpermutation[i])));
    [...]
}
+4
source

BackgroundWorker .NET. COM. , . STA, , , Control.Invoke ( BeginInvoke), ( STA).

+1

, , , - - (a BackgroundWorker, , - , ).

, (.. Dispatcher.BeginInvoke), , , - ...

BackgroundWorkerreveals events such as ProgressChanged(which you can periodically call from your working method) or RunWorkerCompleted(which fires when the main method of work completes).

Using Clipboard.SetTextin any of these events should not throw an exception that you see, and this seems like the preferred way to do something in the user interface thread when working with BackgroundWorker.

0
source

All Articles