xak*_*akz 5 c# task-parallel-library
我有一个类的方法,Task<byte[]> DoSmthAsync()
当我尝试从ViewModel ICommand void方法启动此任务时,它同步启动
void DoSomeCommand()
{
//log managed thread id ...
_someClass.DoSmthAsync().ContinueWith(resultTask => ...);
}
Run Code Online (Sandbox Code Playgroud)
如果我在外部和内部任务中记录CurrentThread.ManagedThreadId它看起来是相同的
Thread #9 - outside
Thread #9 - inside task
Thread #4 - inside inside task // does not matter
Thread #9 - continuation
Run Code Online (Sandbox Code Playgroud)
以异步方式启动此任务我被迫创建具有() => _someClass.DoSmthAsync().ContinueWith(resultTask => ...)操作的新任务并调用Start()它,但我认为这是错误的方法.
我使用.NET 4.0,不能使用async-await,我从来没有遇到过这样的问题顺便说一句.
内部任务创建于TaskCompletionSource:
public Task<byte[]> ProcessDataFromPortAsync(byte[] outData)
{
var tcs = new TaskCompletionSource<byte[]>();
// some event handling ...
WritePortData(outData);
return tcs.Task;
}
Run Code Online (Sandbox Code Playgroud)
不,这是正确的方法。您正在从该方法返回一个任务DoSmthAsync(),如果您遵循 TPL 指南,则必须在异步方法内启动该任务
private Task<byte[]> DoSmthAsync()
{
return Task.Factory.StartNew<byte[]>(() =>
{
// Some stuff.
});
}
Run Code Online (Sandbox Code Playgroud)
然后可以在另一个方法中使用它
private void Method()
{
Task<byte[]> task = DoSmthAsync().ContinueWith(ant =>
{
// Some other stuff.
});
}
Run Code Online (Sandbox Code Playgroud)
我希望这有帮助。
| 归档时间: |
|
| 查看次数: |
679 次 |
| 最近记录: |