Operação "Cross-thread não é válida" ao tentar obter o valor de comboBox
"Cross-thread operation is not valid" exception
Eu experimentei essa exceção muitas vezes, mas todas essas vezes eu estava definindo o valor de um controle. Naquela época eu resolvi usar uma função chamadaSetControlPropertyThreadSafe()
, o que foi sugerido por alguém no stackoverflow.com apenas. Mas desta vez estou recebendo essa exceção quando estou tentando obter o valor de comboBox. Aqui está o código:
string cat;
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text.Trim().Length > 20)
{
System.Threading.Thread t = new System.Threading.Thread(addQuickTopic);
t.Start();
}
else
MessageBox.Show("The length of the title must be greater than 20", "Title length invalid", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
public string tTitle="";
void addQuickTopic()
{
Global.SetControlPropertyThreadSafe(button1, "Text", "Working...");
Global.SetControlPropertyThreadSafe(button1, "Enabled", false);
Topic t = new Topic();
t.setTitle(textBox1.Text);
t.setDescription(" ");
t.setDesID(Global.getMd5Hash(Common.uid+DateTime.Today.ToString()+DateTime.Today.Millisecond.ToString()));
t.setUsrID(Common.uid);
t.setReplyToID("");
t.setConDate("0");
cat = CategoryList.SelectedValue.ToString();
Como você pode ver, estou recebendo o textBox1.Text diretamente sem aplicar nenhuma operação segura. Mas na última linha ao tentar buscar o valor selecionado do comboBox, estou recebendo essa exceção. Então alguém pode me sugerir o que fazer nessa situação? A seguir está o código da minha função de segurança de thread para definir o valor do controle:
public static void SetControlPropertyThreadSafe(Control control, string propertyName, object propertyValue)
{
try
{
if (control.InvokeRequired)
{
control.Invoke(new SetControlPropertyThreadSafeDelegate(SetControlPropertyThreadSafe), new object[] { control, propertyName, propertyValue });
}
else
{
control.GetType().InvokeMember(propertyName, BindingFlags.SetProperty, null, control, new object[] { propertyValue });
}
}
catch (Exception)
{ }
}
Devo precisar criar um similarget
função? Ou alguma outra solução disponível?