What would be the best alternative for the await keyword in .NET 4.0 ? I have a method which needs to return a value after an asynchronous operation. I noticed the wait() method blocks the thread completely thus rendering the asynchronous operation useless. What are my options to run the async operation while still freeing the UI thread ?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Generic Generics in Managed C++
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
I think your basic options are
Task
and.ContinueWith()
async
/await
The easiest way is probably to install the Async CTP. As far as I know the license allows comercial usage. It patches the compiler and comes with a 150kb dll that you can include into your project.
You can use
Task
and.ContinueWith()
. But that means, that you have to take some effort with exeption handling and flow control.Tasks are a functional construct. That's why
ContinueWith()
does not mix well with imperative constructs likefor
loops ortry-catch
blocks. Thereforeasync
andawait
got introduced, so that the compiler can help us out.If you can't have that support of the compiler (i.e. you use .Net 4.0), your best bet is to use the TAP together with a functional framework. Reactive Extensions is a very good framework to treat asynchronous methods.
Just google for "reactive extensions tasks" to get started.
You could implement a behaviour like
await
with theyield
coroutines, i'm using this in non-4.5 code. You need aYieldInstruction
class which is retrieved from the method which should run async:Then you need some implementations of the
YieldInstruction
( a.e.TaskCoroutine
which handles a task ) and use it this way ( Pseudo code ):Now you need a scheduler which handles the execution of the instructions.
When developing WPF or WinForms applications you are also able to avoid any
Invoke
calls if you are updating the coroutines at the right time. You also might be able to extend the idea to make your life even easier. Sample: