اشکال در حل مشکل Cross-thread operation not valid
با سلام به اساتید ارجمند وقتی برنامه رو run میکنم با ارور An unhandled exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll
Additional information: Cross-thread operation not valid: Control 'label1' accessed from a thread other than the thread it was created on. مواجه میشم.
مشکل قطعه کد زیر چیه؟ با سپاس
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
================================================== =============================================
public partial class Form1 : Form
{
Telegram.Bot.Api bot = new Telegram.Bot.Api("337051512:AAGl5b088W1q-_9Z8_y2ZtF8tQ6UIeoszvg");
Thread a;
public Form1()
{
InitializeComponent();
}
public void Getupdates()
{
int offset = 0;
while (true)
{
Telegram.Bot.Types.Update[] updates = bot.GetUpdates(offset).Result;
foreach(var update in updates)
{
offset = update.Id + 1;
if (update.Message == null)
continue;
var from = update.Message.From;
var text = update.Message.Text;
long ChatId = update.Message.Chat.Id;
label1.Text = string.Format("sender : (0)\nText : (1)\nChatid): (2)",from,text,ChatId);
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
a = new Thread(new ThreadStart(Getupdates));
a.Start();
}
نقل قول: اشکال در حل مشکل Cross-thread operation not valid
سلام.
کد زیر رو
CheckForIllegalCrossThreadCalls = false;
به
public Form1()
{
InitializeComponent();
}
اضافه کن
نقل قول: اشکال در حل مشکل Cross-thread operation not valid
نقل قول:
نوشته شده توسط
_behnam_
سلام.
کد زیر رو
CheckForIllegalCrossThreadCalls = false;
به
public Form1()
{
InitializeComponent();
}
اضافه کن
=========================================
بینهایت تشکر بابت این راهنماییتون
میشه خیلی کوتاه بگید مشکلش چی بود؟
نقل قول: اشکال در حل مشکل Cross-thread operation not valid
کنترل هایی که توی ترد UI ساخته شدن رو نباید در تردهای دیگه مقدار دهی کرد.
شما توی متد Getupdates دارید به label1.Text مقدار میدید و بعد این متد رو روی ترد دیگه اجرا میکنید که باعث بروز خطا میشه
راه درستش اینه که مقادیر رو از طریق یه دلیگت به متد BeginInvoke فرم بفرستید تا ترد اصلی مستقیما با اجرای دلیگت تکست باکس رو مقداردهی کنه
خط آخر Getupdates رو به این صورت عوض کنید
string message = string.Format("sender : (0)\nText : (1)\nChatid): (2)",from,text,ChatId);
Action action = () => label1.Text = message;
this.BeginInvoke (action);