Èç¹ûÊÇÐèÒª´«µÝÈ¡ÏûºÍ½ø¶È±¨¸æÔõô°ìÄØ£¿
public async Task<string> ReadTextAsync(string filePath, CancellationToken ct, IProgress<int> progress) { var text = string.Empty; try { using (var stream = await ReadFileAsync(filePath).AsTask(ct, progress)) { using (var reader = new StreamReader(stream)) { text = await reader.ReadToEndAsyncThread().AsTask(ct, progress); } } } catch(OperationCanceledException) {...} return text; }´úÂëµÄ¼ò½à³Ì¶ÈÈÃÄã¸Ðµ½Õ𺳰ɡ£¶øÇҵõ½Task¶ÔÏóºó£¬²»µ«¿ÉÒÔ·½±ãµÄÅäÖÃÈ¡ÏûºÍ½ø¶È±¨¸æ£¬»¹ÄÜͨ¹ýConfigureAwaitÀ´ÅäÖÃSynchronizationContextµÄ»Ö¸´¡£
²»ÖªµÀ²ÎÊýctºÍprogressÔõôÀ´µÄͬѧ¿ÉÒÔ¿´ÉÏһС½ÚµÄÈ¡ÏûºÍÒì²½²¿·Ö¡£
³ýÁËÓÉIAsyncInfoµ½TaskµÄת»»Í⣬»¹¿ÉÒÔÓÉTask/Task<T>תΪIAsyncAction/IAsyncOperation<T>¡£Õâ¸öת»»µÄÖ÷Òª×÷ÓÃÊÇ°ÑC#дµÄ´úÂë·âװΪWinRT¹©ÆäËüÓïÑÔµ÷Óá£ÊµÏÖÕâ¸ö²Ù×÷µÄAsAsyncAction/AsAsyncOperation<T>·½·¨Ò²ÊǶ¨ÒåÓÚÉÏÃæÌáµ½µÄSystem.Runtime.WindowsRuntime.dll³ÌÐò¼¯ÖС£ÒÔ±¾ÎĵÚһС½ÚµÄServiceÀàΪÀý£¬½«ÆäGetUserName·½·¨¸ÄÔì³É·µ»ØIAsyncOperation<string>µÄ·½·¨£¬ÈçÏ£º
public class Service { private readonly Repository _repository; public Service(Repository repository) { _repository = repository; } public IAsyncOperation<string> GetUserName(int id) { var nameAsync = _repository.GetByIdAsync(id).AsAsyncOperation(); return nameAsync; } }ÕâÁ½¸öÀ©Õ¹·½·¨ÊÇÓüòµ¥·½±ã£¬µ«ÓÐÒ»µã²»×ãµÄ¾ÍÊDz»ÄÜÖ§³ÖTaskÖеÄÈ¡ÏûºÍ½ø¶È±¨¸æ¡£Òª½â¾öÕâ¸öÎÊÌâ¿ÉÒÔʹÓÃIAsyncInfoµÄRun·½·¨À´»ñµÃIAsynInfo¶ÔÏó¡£Run·½·¨Ö§³Ö¶àÖÖ²»Í¬ÀàÐ͵ÄίÍжÔÏó×÷Ϊ²ÎÊý£¬±È½Ï¸´ÔÓµÄÒ»ÖÖ¿ÉÒÔÖ§³ÖÈ¡ÏûºÍ½ø¶È±¨¸æ×÷ΪίÍжÔÏó£¨Ò»°ãÊÇlambda±í´ïʽ£©µÄ²ÎÊý£¬±ÈÈç°ÑÉÏÃæµÄÀý×ӸijÉÖ§³ÖÈ¡ÏûºÍ½ø¶È±¨¸æºóÈçÏ£º
public class Service { private readonly Repository _repository; public Service(Repository repository) { _repository = repository; } private async Task<string> GetUserNameInternal(int id, ) { var name = await _repository.GetByIdAsync(id, ct, progress); return name; } public IAsyncOperation<string> GetUserName(int id, CancellationToken ct, IProgress<int> progress) { var nameAsync = AsyncInfo.Run(async (ct, progress)=> { var name = await GetUserNameInternal(id, ct, progress); return name; }; return nameAsync; } }ÄÚÄ»ÕâÑù¾ÍÇáËɵÄʵÏÖÁ˽«C#±àдµÄ´úÂë×÷ΪWinRT×é¼þµÄ¹ý³Ì¡£´ÓÈçÏÂAsAsyncOperationºÍAsyncInfo.RunµÄ·´±àÒë´úÂëÀ´¿´£¬ºÜÄÑÖªµÀÕâ¸ö·½·¨µÄʵÏÖϸ½Ú£¬±Ï¾¹ËüÃǶ¼ÊǺÍWinRT Native´úÂëÏà¹ØµÄ²¿·Ö¡£
WinRTÒì²½±à³Ì C++
΢Èí¶ÔC++½øÐÐÁËÀ©Õ¹£¬Ò»·½ÃæÊÇΪC++ʵÏÖÀàËÆC#ÖлùÓÚTaskµÄÏ̹߳ÜÀí·½Ê½£¬ÁíÒ»·½ÃæÈÃC++(׼ȷ˵ÊÇC++/CX)¿ÉÒÔʵÏÖÓëWinRT¹æ·¶µÄµÄÒì²½½Ó¿Ú»¥²Ù×÷¡£
ÕâЩÀ©Õ¹Ö÷Òª¶¨ÒåÓÚppltask.hÖУ¬concurrencyÃüÃû¿Õ¼äÏ¡£
concurrency::task
¡¡