Answer the question
In order to leave comments, you need to log in
C#. How to write a wait for another thread to execute?
Good afternoon.
There is a method (uploading photos via URL links ) that I want to execute in a separate thread, because my program freezes every time I access the link to the site. Hangs at the moment of accessing the first link (total 300 links) to the image
//data[i].photo2 - прямая ссылка к .jpg
Stream stream = await httpClient.GetStreamAsync(data[i].photo2);
FileStream file = File.OpenWrite(PathForSavePhotos + "/" + data[i].codeProduct + "." + splitFileName[splitFileName.Length - 1]);
await stream.CopyToAsync(file);
try
{
...
}
catch
{
MessageBox.Show("В программе произошла непредвиденная ошибка. Обратитесь к разработчику", "Непредвиденная ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
Answer the question
In order to leave comments, you need to log in
Little context, do you have a console application, WinForms or WPF? If WinForms or WPF - the hang is caused by your code being executed on the UI thread. To begin with, you can try to add to your asynchronous calls, only then you need to remember to redirect all operations with the UI after asynchronous calls to the UI thread ( ).
Further, as already correctly noted in the comments, the try / catch block must be inside the loop (it is not clear from your example how it is located).
In answer to your original question - you probably don't need to allocate a separate thread at all, you can write something like:
Where is an asynchronous method that performs file uploads. Further, where you need to wait - write.ConfigureAwait(false)
Dispatcher.Invoke
_downloadTask = Task.Run(MySuperDownloaderMethod);
await _downloadTask;
If this option does not suit you or you really need a dedicated separate thread, you can create a type field in your class , and after downloading all the images, execute , and where you want to wait, call
If you want something adult, then use AutoResetEvent. You define a field of type in the class , after loading all the files you call where you need to wait -
With a stream, which is inconvenient - you have to explicitly wait for it with , which is not always convenient. In addition, if the thread is not created as a Background and is not completed at the time the program ends, the program will wait for its completion, which is also not always convenient and obvious. Therefore, if there is no hard need for a thread, it is better to use Task.
In general, I recommend readingTaskCompletionSource<object> _downloadTcs = new();
_downloadTcs.SetResult()
await _downloadTcs.Task;
www.albahari.com/threading - a very good read on multithreading.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question