A
A
astrotrain2016-01-09 00:36:30
C++ / C#
astrotrain, 2016-01-09 00:36:30

[C#] How to wait for the end of a thread and perform certain actions?

When I click a button on a form, a thread is launched:

button1_click()
{
t = new Thread(calculate());
t.Start()
 
...
//дождаться завершения треда
 
MessageBox.Show("Выполнено")
 
//полезные действия
...
  
}

After it has completed, I need to perform some actions, but how can I actually wait for it to complete and continue to execute certain logic after that? Thank you.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
P
Peter, 2016-01-09
@petermzg

t.Join();

V
VZVZ, 2016-01-09
@VZVZ

According to Threads, I didn’t really think about it. Why not show that MessageBox in the same calculate method?
If you need to access the GUI - then Invoke to help.
In general, in modern C#, there are tasks (Task) and async-await for asynchrony, and await, by definition, just waits for the task to complete.
He wrote something like this (attention to the word "async" - it is mandatory):

private async void button1_Click(object sender, EventArgs e)
{
    var s = await Task<string>.Factory.StartNew(() => {
        /* Этот код выполняется асинхронно - в отдельном потоке */
        return "Test";
    });
    
    /* А этот код снова в том же потоке */
    MessageBox.Show(s);
}

VS was 2013. But .NET - not 4.5, but 4.0, included the Microsoft Async NuGet package.

X
xmoonlight, 2016-01-09
@xmoonlight

Use coroutines: https://ru.wikipedia.org/wiki/%D0%A1%D0%BE%D0%BF%D...
habrahabr.ru/post/216185

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question