I have a class with methods like Task<byte[]> DoSmthAsync()
When i try to start this Task from ViewModel ICommand void method it launches synchronously
void DoSomeCommand()
{
//log managed thread id ...
_someClass.DoSmthAsync().ContinueWith(resultTask => ...);
}
if i log CurrentThread.ManagedThreadId outside and inside task it appears to be the same
Thread #9 - outside
Thread #9 - inside task
Thread #4 - inside inside task // does not matter
Thread #9 - continuation
to launch this task as async i was forced to create new Task with () => _someClass.DoSmthAsync().ContinueWith(resultTask => ...)
action and call Start()
for it, but i think this is wrong way to do it.
I use .NET 4.0 and can't use async-await, where i never had such problem btw.
Inner task is created with TaskCompletionSource
:
public Task<byte[]> ProcessDataFromPortAsync(byte[] outData)
{
var tcs = new TaskCompletionSource<byte[]>();
// some event handling ...
WritePortData(outData);
return tcs.Task;
}
No that is the right way. You are returning a Task from the DoSmthAsync()
method and if you follow the TPL guidlines, this must be started inside the asynchronious method
private Task<byte[]> DoSmthAsync()
{
return Task.Factory.StartNew<byte[]>(() =>
{
// Some stuff.
});
}
Then this can be consumed in another method
private void Method()
{
Task<byte[]> task = DoSmthAsync().ContinueWith(ant =>
{
// Some other stuff.
});
}
I hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With