Answer the question
In order to leave comments, you need to log in
How to transfer code execution from Queue and yield to a thread (Thread/Task/etc) so as not to freeze the form?
Good afternoon.
There is a C# WinForms .NET 4 - 4.5 application. There is the following code:
public class SuperClass: ClassName
{}
public abstract class ClassName
{
public static IEnumerable<ClassName> GetAll(string param)
{
var queue = new Queue<string>();
var cacheableData = new HashSet<string>();
queue.Enqueue(param);
while (queue.Count > 0)
{
HttpWebRequest request = new HttpWebRequest.Create(param);
// ... логика обработки http запроса
yield return new SubClass {}
// ... еще логика разная
// paramNext = ...
cacheableData.Add(paramNext);
queue.Enqueue(paramNext);
}
}
public class SubClass : ClassName
{ }
}
// .. выполнение кода на форме
var classResult = ClassName.GetAll("xxx");
foreach (ClassName result in classResult )
{
/// что-то делаю с result , заполняю инфу в ListBox
}
Application.DoEvents();
Answer the question
In order to leave comments, you need to log in
It's better to use something like BackgroundWorker. It has a ProgressChanged event through which you can return a ClassName to the main thread.
2 Kerman
I tried to do like this:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
foreach (ClassName result in SuperClass.GetAll("xxx"))
{
worker.ReportProgress(0, result );
}
}
private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
ClassName result = (ClassName )e.UserState;
listBox1.Items.Add(result.Param);
}
Two options.
1. Background Worker. This is a separate thread, it does work (the work method) in a background thread, control is returned to the parent thread either after a change in progress or at the end of the work. There are examples on msdn . Just remember about thread safety - do not change the collection from another thread in the process.
2. Async/await pattern from .net 4.5 This design does not create separate threads and allows everything to be done in the main thread, so it is inherently thread-safe. There are also a bunch of examples on msdn .
Personally, I recommend just copy-pasting the examples from msdn and then gradually changing them to your own code in order to understand what the essence of the methods is and what problems can arise. BackgroundWorker is a rather complex pattern, it is better to understand it first with an elementary example.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question