codingdir logo sitemap sitemap |

Cross-thread operation not valid when using Invoke

By : , Category : c#

If the value of the receivedMessage variable changes before the invoked Action executes, the new value of that variable will be used - if it's functioning in the same way as your messageTb.Text example, the value is cleared immediately, and the invoked Action will only see the post-Clear blank value. Try copying the usersName.Text + ": " + receivedMessage string into a single-use variable and referencing that in your Invoke, e.g.

string newMessage = usersName.Text + ": " + receivedMessage;
Invoke(new Action(() => messageBox.Items.Add(newMessage)));
ReLated :

You are trying to update UI in a non-UI thread. You can dismiss this exception by using below code to change pictureBox4.Refresh() or other similar access code to sth as below:

pictureBox4.InvokeIfRequired(() =>
    // Do anything you want with the control here

You must invoke using the UI thread, you cannot update the UI on a thread that you created, you must use the forms invoke method or the controls...

Try this:

this.BeginInvoke((Action)(() => toolStripStatusLabel1.Text = "This text was set safely."));

You should always make sure that when you access elements of the UI that you do so on the UI thread otherwise you can get the error you're experiencing.

The easiest way to avoid this issue is to separate out the code that reads the data from the UI and the code that writes your Excel file.

First start by defining a simple class to hold your data:

Private Class BgwData
    Public FileName As String
    Public Headers As String()
    Public Data As String()()
End Class

I defined this inside the form class as it doesn't need to be exposed outside of the form.

Now the code that calls the background worker needs to change so that an instance of BgwData is created, populated with the data from the ListView, as well as the file name, and sent to the worker as its argument.

Dim data As New BgwData() With _
{ _
    .FileName = saveFileDialog1.FileName, _
    .Headers = _
        Me.ListView1.Columns _
            .Cast(Of System.Windows.Forms.ColumnHeader)() _
            .Select(Function(ch) ch.Name) _
            .ToArray(), _
    .Data = _
        Me.ListView1.Items.Cast(Of ListViewItem)() _
            .Select(Function(lvi) lvi.SubItems _
                    .Cast(Of ListViewItem.ListViewSubItem)() _
                    .Select(Function(lvsi) lvsi.Text) _
                    .ToArray()) _
            .ToArray() _


This code runs in the PictureBox2_Click so is still on the UI thread.

The BackgroundWorker1_DoWork method changes slightly to call saveExcelFile like this:

saveExcelFile(CType(e.Argument, BgwData))

The signature for saveExcelFile changes to Private Sub saveExcelFile(ByVal data As BgwData)

And the code that populates the spreadsheet becomes:

Dim row As Integer = 1
Dim col As Integer = 1
For i = 0 To data.Headers.Length - 1
    sheet.Cells(1, i + 1) = data.Headers(i)
For i = 0 To data.Data.Length - 1
    For j = 0 To data.Data(i).Length - 1
        sheet.Cells(i + 2, j + 1) = data.Data(i)(j)

And, of course, there is a small change to the SaveAs method call to become:


Also, as a side note, do keep in mind that you need release your COM objects after you use them too:


Message :
Login to Add Your Comments .
How to disable registered OpenCL platforms on Windows?
Is Observable broken in Angular 2 Beta 3?
Cross-thread operation not valid when using Invoke
How to pass an IEnumerable or queryable list of properties from Controller to View
Finding numbers after a certain keyword using Python
Pocketsphinx recognizes random phrases in a silence
Passing non-thread-safe objects through thread-safe containers
React scroll nav
BizTalk WCF-BasicHttp Adapter does not allow Empty string for Service Certificate Props
Why property ''cause" of Exception is repeating forever?
Privacy Policy 2017 © All Rights Reserved .