c# – BackgroundWorker和剪贴板

前端之家收集整理的这篇文章主要介绍了c# – BackgroundWorker和剪贴板前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我用一个简单的代码疯狂,我使用BackgroundWorker来自动执行基本操作.我应该向剪贴板添加内容吗?

在BackgroundWorker的方法中执行此代码后:

Clipboard.SetText (splitpermutation [i]);

我得到一个错误,解释线程必须是STA,但我不明白该怎么做.
这里有更多代码:(不是全部)

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]);
        [...]
    }
}

解决方法

您可以将其封送到UI线程以使其工作:
else
{
    [...]
    this.Dispatcher.BeginInvoke(new Action(() => Clipboard.SetText(splitpermutation[i])));
    [...]
}

猜你在找的C#相关文章