Can I use task.Wait(); like that? Note that when I call task.Wait the task is probably already finished.

And probably you can suggest better pattern.

class A {

...
public void Connect() {
stayConnected = true;
while (stayConnected) {
....
}
LongRunning);
while (stayConnected) {
....
}
LongRunning);
}

private volatile bool stayConnected;

// should be synchronous. when return everything should be disconected
public void Disconnect() {
stayConnected = false;
}

}

-

You can use a CancellationToken and Task.WaitAll(...) to do this...

public class A
{
private readonly CancellationTokenSource tokenSource = new CancellationTokenSource();

public void Connect()
{
}

public void Disconnect()
{
tokenSource.Cancel();
}

public void SomeWork(object o)
{
CancellationToken token = (CancellationToken)o;
while (!token.IsCancellationRequested)
{
Console.WriteLine("working...");
}
}
}


-
why cancellationtoken is better than just "volatile boolean"? in general i prefer "easy to port to c++" code. –  javapowered Nov 29 '12 at 15:54
I think CancellationToken should be used when you want to cancel a Task prematurely. I think that's not the case here. Also, canceling the Task properly (which you didn't do) would mean WaitAll() would throw an exception. –  svick Nov 29 '12 at 16:39
You can certainly use volatile if you want to keep it simple. –  Alechandro Nov 29 '12 at 16:48
@svick why does it throw an exception? –  Alechandro Nov 29 '12 at 17:01
@Alechandro Because the Tasks would be canceled. Wait() and WaitAll() throw an exception when you wait on a canceled Task. –  svick Nov 29 '12 at 17:51

Task.Wait() should just return true if the task is completed, so sure you can. However, you should better use waiting with timeout or TimeSpan parameter if you have actions inside of while { } loop that can possibly cause a freeze.

-
Task.Wait() without a timeout doesn't return anything. –  svick Nov 29 '12 at 18:41

This seems like a reasonable approach to me. You could improve it a bit by using Task.WaitAll() but that won't change much.

Also, I wouldn't set the fields to null unless I had good reason to do it. Yeah, those Tasks are not useful for anything anymore, but they are also almost free.

-