C# - How do you access information in form controls from a backgroundworker thread [duplicate]

StackOverflow https://stackoverflow.com/questions/22847753

Вопрос

I have seen several threads on how to make changes to UI elements from a background worker, but my problem is with the opposite process. I have a ListView which contains a number of items with check boxes next to them. I have a backgroundworker that should write out data to a csv for the items that are checked in the ListView. My problem is that I am unable to access the ListView.CheckedItems list which is stored on my main form. Is there an elegant way to access this data from the backgroundworker, or do I have to use some terrible workaround where I store the list in the arguments of the EventArgs parameter?

As an example, the following code would create a directory for every checked entry if there were no cross-threading problems:

private void WriteToCSV(Dictionary<string,PointPairList> curves)
    {
    foreach (KeyValuePair<string, PointPairList> entry in curves)
        {
            if (SaveListView.CheckedItems.ContainsKey(entry.Key))
            {
                string curveDir = Path.Combine(this.dirString, entry.Key);
                if (!Directory.Exists(curveDir))
                {
                    Directory.CreateDirectory(curveDir);
                }
            }
        }
    }

So the issue is, if this method is called from a backgroundworker, and "SaveListView" is a listview on the main form, how can I access SaveListView without raising a cross-threading exception?

Thank you for anything you can do.

Это было полезно?

Решение

The elegant way of doing this is to create a list of only the data (such as directories) you are interested in and pass it to the BackgroundWorker's DoWorkEventArgs.

You should never pass Forms controls to a BackgroundWorker; doing that can cause cross-thread exceptions, crash your UI, and cause race conditions as both the UI and worker try to use the same data. Only pass the data you actually need to another thread.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top