简体   繁体   English

在.net 4.0中启动任务的正确方法

[英]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 我有一个类的方法,如Task<byte[]> DoSmthAsync()当我尝试从ViewModel ICommand void方法启动此任务时,它同步启动

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 如果我在外部和内部任务中记录CurrentThread.ManagedThreadId它看起来是相同的

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. 以异步方式启动此任务我被迫用() => _someClass.DoSmthAsync().ContinueWith(resultTask => ...)动作创建新任务并为它调用Start() ,但我认为这是错误的方法做到这一点。

I use .NET 4.0 and can't use async-await, where i never had such problem btw. 我使用.NET 4.0,不能使用async-await,我从来没有遇到过这样的问题顺便说一句。

Inner task is created with TaskCompletionSource : 使用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 您正在从DoSmthAsync()方法返回一个Task,如果您遵循TPL指南,则必须在异步方法中启动

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. 我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM