Есть класс:
namespace LiveInternet
{
public class CategoryEventArgs : EventArgs
{
public string listCategory { get; private set; }
public CategoryEventArgs(string listCategory)
{
this.listCategory = listCategory;
}
}
// Объявление делегата для события
public delegate void CategoryEventHandler(object sender, CategoryEventArgs e);
public event CategoryEventHandler CategoryReceived;
public void GetCategory()
{
// Запуск потока
Thread catThread = new Thread(new ThreadStart(ThGetCategory));
catThread.Start();
}
private void ThGetCategory()
{
// Вызов события из потока
...
...
if (CategoryReceived != null)
{
CategoryReceived(this, new CategoryEventArgs(_listCategory));
}
...
...
}
Класс используется следующим образом:
...
...
using LiveInternet;
namespace LiveRating
{
public partial class frmLiveRating : Form
{
Rating liveRating = new Rating();
private void frmLiveRating_Load(object sender, EventArgs e)
{
// Подписываемся на событие[/COLOR]
liveRating.CategoryReceived += new Rating.CategoryEventHandler(liveRating_CategoryReceived);
// Вызываем метод класса, он запускает поток
liveRating.GetCategory();
}
[COLOR=Green]// Произошло событие[/COLOR]
void liveRating_CategoryReceived(object sender, CategoryEventArgs e)
{
// Обращение к визуальному объекту
comboCategory.Items.Clear();
// Вызывает ошибку: Cross-thread operation not valid: Control 'comboCategory' accessed from a thread other than the thread it was created on.
}
}
}
Вылетает ошибка:
Cross-thread operation not valid: Control 'comboCategory' accessed from a thread other than the thread it was created on.
Есть способ использовать в самом обработчике события (liveRating_CategoryReceived) метод Invoke, но это как-то неправильно.
Много гугли, находил схожие вопросы, но ответов на них не было.
Вопрос:
Как вызвать,
именно вызвать, потокобезопасное событие?