Answer the question
In order to leave comments, you need to log in
Accessing a Windows Forms Control from Another Thread (C#)?
I'm trying to write a program whose main code will be executed in another thread and add data to the ListBox as I work.
Log is an object of type ListBox.
Creating a thread:
private void bGo_Click(object sender, EventArgs e)
{
...
Log.Items.Add("Старт");
Thread t = new Thread(Download);
t.Start();
t.Join();
...
}
void Download()
{
for (int i = 0; i <= 2; i ++)
{
for (int j = 0; j <= 1000; j += 100)
{
Thread.Sleep(100);
//реальный код слал запросы в сеть,
//т.е. большую часть времени простаивал
WriteToLog("test");
}
}
}
void WriteToLog(string message)
{
if (Log.InvokeRequired)
{
Log.BeginInvoke(new Action<string>((s)
=> Log.Items.Add(s)), message);
}
else
{
Log.Items.Add(message);
}
}
Answer the question
In order to leave comments, you need to log in
Since .net 4.0 is used, it is better to use tasks instead of threads:
Task task = new Task(Download);
task.ContinueWith(CodeAfterJoin);
task.Start();
Explanatory description of threads here www.rsdn.ru/article/dotnet/CSThreading1.xml
>If you replace BeginInvoke with Invoke, the program hangs on this line for an indefinite time. How to make a normal conclusion?
Because you are using t.Join();
As mentioned above, nothing will work with Join(), because you are waiting for the thread to complete.
In general, look towards asynchronous programming and the BackgroundWorker class.
msdn.microsoft.com/en-us/library/ms228969.aspx
Try like this:
delegate void WriteToLogDelegate(string message);
void WriteToLog(string message)
{
if (Log.InvokeRequired)
{
var writeToLog = new WriteToLogDelegate(WriteToLog);
Log.Invoke(writeToLog, message);
}
else
{
Log.Items.Add(message);
}
}
private delegate void UpdateListBox(string test);
static object locker = new object();
private void UpLB(string test)
{
lock (locker)
{
Log.Items.Add(test);
}
}
//После чего вызываете
this.Invoke(new UpdateListBox(this.UpLB),new object[] { m.Message});
Try like this
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question