Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to start Task in .net 4.0

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;
}
like image 796
xakpc Avatar asked Nov 10 '22 09:11

xakpc


1 Answers

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.

like image 123
MoonKnight Avatar answered Nov 14 '22 22:11

MoonKnight