pplxtasks.h 312 KB
Newer Older
藤森雅人's avatar
藤森雅人 committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***
 * Copyright (C) Microsoft. All rights reserved.
 * Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
 *
 * =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
 *
 * Parallel Patterns Library - PPLx Tasks
 *
 * For the latest on this and related APIs, please see: https://github.com/Microsoft/cpprestsdk
 *
 * =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
 ****/

#pragma once

#ifndef PPLXTASKS_H
#define PPLXTASKS_H

#include "cpprest/details/cpprest_compat.h"

#if (defined(_MSC_VER) && (_MSC_VER >= 1800)) && !CPPREST_FORCE_PPLX
#include <ppltasks.h>
namespace pplx = Concurrency;

namespace Concurrency
{
/// <summary>
/// Sets the ambient scheduler to be used by the PPL constructs.
/// </summary>
_ASYNCRTIMP void __cdecl set_cpprestsdk_ambient_scheduler(const std::shared_ptr<scheduler_interface>& _Scheduler);

/// <summary>
/// Gets the ambient scheduler to be used by the PPL constructs
/// </summary>
_ASYNCRTIMP const std::shared_ptr<scheduler_interface>& __cdecl get_cpprestsdk_ambient_scheduler();

} // namespace Concurrency

#if (_MSC_VER >= 1900)
#include <concrt.h>
namespace Concurrency
{
namespace extensibility
{
typedef ::std::condition_variable condition_variable_t;
typedef ::std::mutex critical_section_t;
typedef ::std::unique_lock<::std::mutex> scoped_critical_section_t;

typedef ::Concurrency::event event_t;
typedef ::Concurrency::reader_writer_lock reader_writer_lock_t;
typedef ::Concurrency::reader_writer_lock::scoped_lock scoped_rw_lock_t;
typedef ::Concurrency::reader_writer_lock::scoped_lock_read scoped_read_lock_t;

typedef ::Concurrency::details::_ReentrantBlockingLock recursive_lock_t;
typedef recursive_lock_t::_Scoped_lock scoped_recursive_lock_t;
} // namespace extensibility
} // namespace Concurrency
#endif // _MSC_VER >= 1900
#else

#include "pplx/pplx.h"

#if defined(__ANDROID__)
#include <jni.h>
void cpprest_init(JavaVM*);
#endif

// Cannot build using a compiler that is older than dev10 SP1
#if defined(_MSC_VER)
#if _MSC_FULL_VER < 160040219 /*IFSTRIP=IGN*/
#error ERROR: Visual Studio 2010 SP1 or later is required to build ppltasks
#endif /*IFSTRIP=IGN*/
#endif /* defined(_MSC_VER) */

#include <algorithm>
#include <atomic>
#include <exception>
#include <functional>
#include <utility>
#include <vector>

#if defined(_MSC_VER)
#include <intrin.h>
#if defined(__cplusplus_winrt)
#include <agile.h>
#include <ctxtcall.h>
#include <winapifamily.h>

#include <windows.h>
#ifndef _UITHREADCTXT_SUPPORT

#ifdef WINAPI_FAMILY /*IFSTRIP=IGN*/

// It is safe to include winapifamily as WINAPI_FAMILY was defined by the user
#include <winapifamily.h>

#if WINAPI_FAMILY == WINAPI_FAMILY_APP
// UI thread context support is not required for desktop and Windows Store apps
#define _UITHREADCTXT_SUPPORT 0
#elif WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP
// UI thread context support is not required for desktop and Windows Store apps
#define _UITHREADCTXT_SUPPORT 0
#else /* WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP */
#define _UITHREADCTXT_SUPPORT 1
#endif /* WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP */

#else /* WINAPI_FAMILY */
// Not supported without a WINAPI_FAMILY setting.
#define _UITHREADCTXT_SUPPORT 0
#endif /* WINAPI_FAMILY */

#endif /* _UITHREADCTXT_SUPPORT */

#if _UITHREADCTXT_SUPPORT
#include <uithreadctxt.h>
#endif /* _UITHREADCTXT_SUPPORT */

#pragma detect_mismatch("PPLXTASKS_WITH_WINRT", "1")
#else /* defined(__cplusplus_winrt) */
#pragma detect_mismatch("PPLXTASKS_WITH_WINRT", "0")
#endif /* defined(__cplusplus_winrt) */
#endif /* defined(_MSC_VER) */

#ifdef _DEBUG
#define _DBG_ONLY(X) X
#else
#define _DBG_ONLY(X)
#endif // #ifdef _DEBUG

// std::copy_exception changed to std::make_exception_ptr from VS 2010 to VS 11.
#ifdef _MSC_VER
#if _MSC_VER < 1700 /*IFSTRIP=IGN*/
namespace std
{
template<class _E>
exception_ptr make_exception_ptr(_E _Except)
{
    return copy_exception(_Except);
}
} // namespace std
#endif              /* _MSC_VER < 1700 */
#ifndef PPLX_TASK_ASYNC_LOGGING
#if _MSC_VER >= 1800 && defined(__cplusplus_winrt)
#define PPLX_TASK_ASYNC_LOGGING 1 // Only enable async logging under dev12 winrt
#else
#define PPLX_TASK_ASYNC_LOGGING 0
#endif
#endif /* !PPLX_TASK_ASYNC_LOGGING */
#endif /* _MSC_VER */

#pragma pack(push, _CRT_PACKING)

#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable : 28197)
#pragma warning(disable : 4100) // Unreferenced formal parameter - needed for document generation
#pragma warning(disable : 4127) // constant express in if condition - we use it for meta programming
#endif                          /* defined(_MSC_VER) */

// All CRT public header files are required to be protected from the macro new
#pragma push_macro("new")
#undef new

// stuff ported from Dev11 CRT
// NOTE: this doesn't actually match std::declval. it behaves differently for void!
// so don't blindly change it to std::declval.
namespace stdx
{
template<class _T>
_T&& declval();
}

/// <summary>
///     The <c>pplx</c> namespace provides classes and functions that give you access to the Concurrency Runtime,
///     a concurrent programming framework for C++. For more information, see <see cref="Concurrency Runtime"/>.
/// </summary>
/**/
namespace pplx
{
/// <summary>
///     A type that represents the terminal state of a task. Valid values are <c>completed</c> and <c>canceled</c>.
/// </summary>
/// <seealso cref="task Class"/>
/**/
typedef task_group_status task_status;

template<typename _Type>
class task;
template<>
class task<void>;

// In debug builds, default to 10 frames, unless this is overridden prior to #includ'ing ppltasks.h.  In retail builds,
// default to only one frame.
#ifndef PPLX_TASK_SAVE_FRAME_COUNT
#ifdef _DEBUG
#define PPLX_TASK_SAVE_FRAME_COUNT 10
#else
#define PPLX_TASK_SAVE_FRAME_COUNT 1
#endif
#endif

/// <summary>
/// Helper macro to determine how many stack frames need to be saved. When any number less or equal to 1 is specified,
/// only one frame is captured and no stackwalk will be involved. Otherwise, the number of callstack frames will be
/// captured.
/// </summary>
/// <ramarks>
/// This needs to be defined as a macro rather than a function so that if we're only gathering one frame,
/// _ReturnAddress() will evaluate to client code, rather than a helper function inside of _TaskCreationCallstack,
/// itself.
/// </remarks>
#if PPLX_TASK_SAVE_FRAME_COUNT > 1
#if defined(__cplusplus_winrt) && !defined(_DEBUG)
#pragma message(                                                                                                       \
    "WARNING: Redefining PPLX_TASK_SAVE_FRAME_COUNT under Release build for non-desktop applications is not supported; only one frame will be captured!")
#define PPLX_CAPTURE_CALLSTACK() ::pplx::details::_TaskCreationCallstack::_CaptureSingleFrameCallstack(_ReturnAddress())
#else
#define PPLX_CAPTURE_CALLSTACK()                                                                                       \
    ::pplx::details::_TaskCreationCallstack::_CaptureMultiFramesCallstack(PPLX_TASK_SAVE_FRAME_COUNT)
#endif
#else
#define PPLX_CAPTURE_CALLSTACK() ::pplx::details::_TaskCreationCallstack::_CaptureSingleFrameCallstack(_ReturnAddress())
#endif

/// <summary>
///     Returns an indication of whether the task that is currently executing has received a request to cancel its
///     execution. Cancellation is requested on a task if the task was created with a cancellation token, and
///     the token source associated with that token is canceled.
/// </summary>
/// <returns>
///     <c>true</c> if the currently executing task has received a request for cancellation, <c>false</c> otherwise.
/// </returns>
/// <remarks>
///     If you call this method in the body of a task and it returns <c>true</c>, you must respond with a call to
///     <see cref="cancel_current_task Function">cancel_current_task</see> to acknowledge the cancellation request,
///     after performing any cleanup you need. This will abort the execution of the task and cause it to enter into
///     the <c>canceled</c> state. If you do not respond and continue execution, or return instead of calling
///     <c>cancel_current_task</c>, the task will enter the <c>completed</c> state when it is done.
///     state.
///     <para>A task is not cancelable if it was created without a cancellation token.</para>
/// </remarks>
/// <seealso cref="task Class"/>
/// <seealso cref="cancellation_token_source Class"/>
/// <seealso cref="cancellation_token Class"/>
/// <seealso cref="cancel_current_task Function"/>
/**/
inline bool _pplx_cdecl is_task_cancellation_requested()
{
    return ::pplx::details::_TaskCollection_t::_Is_cancellation_requested();
}

/// <summary>
///     Cancels the currently executing task. This function can be called from within the body of a task to abort the
///     task's execution and cause it to enter the <c>canceled</c> state. While it may be used in response to
///     the <see cref="is_task_cancellation_requested Function">is_task_cancellation_requested</see> function, you may
///     also use it by itself, to initiate cancellation of the task that is currently executing.
///     <para>It is not a supported scenario to call this function if you are not within the body of a <c>task</c>.
///     Doing so will result in undefined behavior such as a crash or a hang in your application.</para>
/// </summary>
/// <seealso cref="task Class"/>
/**/
inline __declspec(noreturn) void _pplx_cdecl cancel_current_task() { throw task_canceled(); }

namespace details
{
/// <summary>
///     Callstack container, which is used to capture and preserve callstacks in ppltasks.
///     Members of this class is examined by vc debugger, thus there will be no public access methods.
///     Please note that names of this class should be kept stable for debugger examining.
/// </summary>
class _TaskCreationCallstack
{
private:
    // If _M_SingleFrame != nullptr, there will be only one frame of callstacks, which is stored in _M_SingleFrame;
    // otherwise, _M_Frame will store all the callstack frames.
    void* _M_SingleFrame;
    std::vector<void*> _M_frames;

public:
    _TaskCreationCallstack() { _M_SingleFrame = nullptr; }

    // Store one frame of callstack. This function works for both Debug / Release CRT.
    static _TaskCreationCallstack _CaptureSingleFrameCallstack(void* _SingleFrame)
    {
        _TaskCreationCallstack _csc;
        _csc._M_SingleFrame = _SingleFrame;
        return _csc;
    }

    // Capture _CaptureFrames number of callstack frames. This function only work properly for Desktop or Debug CRT.
    __declspec(noinline) static _TaskCreationCallstack _CaptureMultiFramesCallstack(size_t _CaptureFrames)
    {
        _TaskCreationCallstack _csc;
        _csc._M_frames.resize(_CaptureFrames);
        // skip 2 frames to make sure callstack starts from user code
        _csc._M_frames.resize(::pplx::details::platform::CaptureCallstack(&_csc._M_frames[0], 2, _CaptureFrames));
        return _csc;
    }
};
typedef unsigned char _Unit_type;

struct _TypeSelectorNoAsync
{
};
struct _TypeSelectorAsyncOperationOrTask
{
};
struct _TypeSelectorAsyncOperation : public _TypeSelectorAsyncOperationOrTask
{
};
struct _TypeSelectorAsyncTask : public _TypeSelectorAsyncOperationOrTask
{
};
struct _TypeSelectorAsyncAction
{
};
struct _TypeSelectorAsyncActionWithProgress
{
};
struct _TypeSelectorAsyncOperationWithProgress
{
};

template<typename _Ty>
struct _NormalizeVoidToUnitType
{
    typedef _Ty _Type;
};

template<>
struct _NormalizeVoidToUnitType<void>
{
    typedef _Unit_type _Type;
};

template<typename _T>
struct _IsUnwrappedAsyncSelector
{
    static const bool _Value = true;
};

template<>
struct _IsUnwrappedAsyncSelector<_TypeSelectorNoAsync>
{
    static const bool _Value = false;
};

template<typename _Ty>
struct _UnwrapTaskType
{
    typedef _Ty _Type;
};

template<typename _Ty>
struct _UnwrapTaskType<task<_Ty>>
{
    typedef _Ty _Type;
};

template<typename _T>
_TypeSelectorAsyncTask _AsyncOperationKindSelector(task<_T>);

_TypeSelectorNoAsync _AsyncOperationKindSelector(...);

#if defined(__cplusplus_winrt)
template<typename _Type>
struct _Unhat
{
    typedef _Type _Value;
};

template<typename _Type>
struct _Unhat<_Type ^>
{
    typedef _Type _Value;
};

value struct _NonUserType
{
public:
    int _Dummy;
};

template<typename _Type, bool _IsValueTypeOrRefType = __is_valid_winrt_type(_Type)>
struct _ValueTypeOrRefType
{
    typedef _NonUserType _Value;
};

template<typename _Type>
struct _ValueTypeOrRefType<_Type, true>
{
    typedef _Type _Value;
};

template<typename _T1, typename _T2>
_T2 _ProgressTypeSelector(Windows::Foundation::IAsyncOperationWithProgress<_T1, _T2> ^);

template<typename _T1>
_T1 _ProgressTypeSelector(Windows::Foundation::IAsyncActionWithProgress<_T1> ^);

template<typename _Type>
struct _GetProgressType
{
    typedef decltype(_ProgressTypeSelector(stdx::declval<_Type>())) _Value;
};

template<typename _Type>
struct _IsIAsyncInfo
{
    static const bool _Value = __is_base_of(Windows::Foundation::IAsyncInfo, typename _Unhat<_Type>::_Value);
};

template<typename _T>
_TypeSelectorAsyncOperation _AsyncOperationKindSelector(Windows::Foundation::IAsyncOperation<_T> ^);

_TypeSelectorAsyncAction _AsyncOperationKindSelector(Windows::Foundation::IAsyncAction ^);

template<typename _T1, typename _T2>
_TypeSelectorAsyncOperationWithProgress _AsyncOperationKindSelector(
    Windows::Foundation::IAsyncOperationWithProgress<_T1, _T2> ^);

template<typename _T>
_TypeSelectorAsyncActionWithProgress _AsyncOperationKindSelector(Windows::Foundation::IAsyncActionWithProgress<_T> ^);

template<typename _Type, bool _IsAsync = _IsIAsyncInfo<_Type>::_Value>
struct _TaskTypeTraits
{
    typedef typename _UnwrapTaskType<_Type>::_Type _TaskRetType;
    typedef decltype(_AsyncOperationKindSelector(stdx::declval<_Type>())) _AsyncKind;
    typedef typename _NormalizeVoidToUnitType<_TaskRetType>::_Type _NormalizedTaskRetType;

    static const bool _IsAsyncTask = _IsAsync;
    static const bool _IsUnwrappedTaskOrAsync = _IsUnwrappedAsyncSelector<_AsyncKind>::_Value;
};

template<typename _Type>
struct _TaskTypeTraits<_Type, true>
{
    typedef decltype(((_Type) nullptr)->GetResults()) _TaskRetType;
    typedef _TaskRetType _NormalizedTaskRetType;
    typedef decltype(_AsyncOperationKindSelector((_Type) nullptr)) _AsyncKind;

    static const bool _IsAsyncTask = true;
    static const bool _IsUnwrappedTaskOrAsync = _IsUnwrappedAsyncSelector<_AsyncKind>::_Value;
};

#else  /* defined (__cplusplus_winrt) */
template<typename _Type>
struct _IsIAsyncInfo
{
    static const bool _Value = false;
};

template<typename _Type, bool _IsAsync = false>
struct _TaskTypeTraits
{
    typedef typename _UnwrapTaskType<_Type>::_Type _TaskRetType;
    typedef decltype(_AsyncOperationKindSelector(stdx::declval<_Type>())) _AsyncKind;
    typedef typename _NormalizeVoidToUnitType<_TaskRetType>::_Type _NormalizedTaskRetType;

    static const bool _IsAsyncTask = false;
    static const bool _IsUnwrappedTaskOrAsync = _IsUnwrappedAsyncSelector<_AsyncKind>::_Value;
};
#endif /* defined (__cplusplus_winrt) */

template<typename _Function>
auto _IsCallable(_Function _Func, int) -> decltype(_Func(), std::true_type())
{
    (void)(_Func);
    return std::true_type();
}
template<typename _Function>
std::false_type _IsCallable(_Function, ...)
{
    return std::false_type();
}

template<>
struct _TaskTypeTraits<void>
{
    typedef void _TaskRetType;
    typedef _TypeSelectorNoAsync _AsyncKind;
    typedef _Unit_type _NormalizedTaskRetType;

    static const bool _IsAsyncTask = false;
    static const bool _IsUnwrappedTaskOrAsync = false;
};

template<typename _Type>
task<_Type> _To_task(_Type t);

template<typename _Func>
task<void> _To_task_void(_Func f);

struct _BadContinuationParamType
{
};

template<typename _Function, typename _Type>
auto _ReturnTypeHelper(_Type t, _Function _Func, int, int) -> decltype(_Func(_To_task(t)));
template<typename _Function, typename _Type>
auto _ReturnTypeHelper(_Type t, _Function _Func, int, ...) -> decltype(_Func(t));
template<typename _Function, typename _Type>
auto _ReturnTypeHelper(_Type t, _Function _Func, ...) -> _BadContinuationParamType;

template<typename _Function, typename _Type>
auto _IsTaskHelper(_Type t, _Function _Func, int, int) -> decltype(_Func(_To_task(t)), std::true_type());
template<typename _Function, typename _Type>
std::false_type _IsTaskHelper(_Type t, _Function _Func, int, ...);

template<typename _Function>
auto _VoidReturnTypeHelper(_Function _Func, int, int) -> decltype(_Func(_To_task_void(_Func)));
template<typename _Function>
auto _VoidReturnTypeHelper(_Function _Func, int, ...) -> decltype(_Func());

template<typename _Function>
auto _VoidIsTaskHelper(_Function _Func, int, int) -> decltype(_Func(_To_task_void(_Func)), std::true_type());
template<typename _Function>
std::false_type _VoidIsTaskHelper(_Function _Func, int, ...);

template<typename _Function, typename _ExpectedParameterType>
struct _FunctionTypeTraits
{
    typedef decltype(
        _ReturnTypeHelper(stdx::declval<_ExpectedParameterType>(), stdx::declval<_Function>(), 0, 0)) _FuncRetType;
    static_assert(!std::is_same<_FuncRetType, _BadContinuationParamType>::value,
                  "incorrect parameter type for the callable object in 'then'; consider _ExpectedParameterType or "
                  "task<_ExpectedParameterType> (see below)");

    typedef decltype(
        _IsTaskHelper(stdx::declval<_ExpectedParameterType>(), stdx::declval<_Function>(), 0, 0)) _Takes_task;
};

template<typename _Function>
struct _FunctionTypeTraits<_Function, void>
{
    typedef decltype(_VoidReturnTypeHelper(stdx::declval<_Function>(), 0, 0)) _FuncRetType;
    typedef decltype(_VoidIsTaskHelper(stdx::declval<_Function>(), 0, 0)) _Takes_task;
};

template<typename _Function, typename _ReturnType>
struct _ContinuationTypeTraits
{
    typedef task<
        typename _TaskTypeTraits<typename _FunctionTypeTraits<_Function, _ReturnType>::_FuncRetType>::_TaskRetType>
        _TaskOfType;
};

// _InitFunctorTypeTraits is used to decide whether a task constructed with a lambda should be unwrapped. Depending on
// how the variable is declared, the constructor may or may not perform unwrapping. For eg.
//
//  This declaration SHOULD NOT cause unwrapping
//    task<task<void>> t1([]() -> task<void> {
//        task<void> t2([]() {});
//        return t2;
//    });
//
// This declaration SHOULD cause unwrapping
//    task<void>> t1([]() -> task<void> {
//        task<void> t2([]() {});
//        return t2;
//    });
// If the type of the task is the same as the return type of the function, no unwrapping should take place. Else normal
// rules apply.
template<typename _TaskType, typename _FuncRetType>
struct _InitFunctorTypeTraits
{
    typedef typename _TaskTypeTraits<_FuncRetType>::_AsyncKind _AsyncKind;
    static const bool _IsAsyncTask = _TaskTypeTraits<_FuncRetType>::_IsAsyncTask;
    static const bool _IsUnwrappedTaskOrAsync = _TaskTypeTraits<_FuncRetType>::_IsUnwrappedTaskOrAsync;
};

template<typename T>
struct _InitFunctorTypeTraits<T, T>
{
    typedef _TypeSelectorNoAsync _AsyncKind;
    static const bool _IsAsyncTask = false;
    static const bool _IsUnwrappedTaskOrAsync = false;
};

/// <summary>
///     Helper object used for LWT invocation.
/// </summary>
struct _TaskProcThunk
{
    _TaskProcThunk(const std::function<void()>& _Callback) : _M_func(_Callback) {}

    static void _pplx_cdecl _Bridge(void* _PData)
    {
        _TaskProcThunk* _PThunk = reinterpret_cast<_TaskProcThunk*>(_PData);
        _Holder _ThunkHolder(_PThunk);
        _PThunk->_M_func();
    }

private:
    // RAII holder
    struct _Holder
    {
        _Holder(_TaskProcThunk* _PThunk) : _M_pThunk(_PThunk) {}

        ~_Holder() { delete _M_pThunk; }

        _TaskProcThunk* _M_pThunk;

    private:
        _Holder& operator=(const _Holder&);
    };

    std::function<void()> _M_func;
    _TaskProcThunk& operator=(const _TaskProcThunk&);
};

/// <summary>
///     Schedule a functor with automatic inlining. Note that this is "fire and forget" scheduling, which cannot be
///     waited on or canceled after scheduling.
///     This schedule method will perform automatic inlining base on <paramref value="_InliningMode"/>.
/// </summary>
/// <param name="_Func">
///     The user functor need to be scheduled.
/// </param>
/// <param name="_InliningMode">
///     The inlining scheduling policy for current functor.
/// </param>
static void _ScheduleFuncWithAutoInline(const std::function<void()>& _Func, _TaskInliningMode_t _InliningMode)
{
    _TaskCollection_t::_RunTask(&_TaskProcThunk::_Bridge, new _TaskProcThunk(_Func), _InliningMode);
}

class _ContextCallback
{
    typedef std::function<void(void)> _CallbackFunction;

#if defined(__cplusplus_winrt)

public:
    static _ContextCallback _CaptureCurrent()
    {
        _ContextCallback _Context;
        _Context._Capture();
        return _Context;
    }

    ~_ContextCallback() { _Reset(); }

    _ContextCallback(bool _DeferCapture = false)
    {
        if (_DeferCapture)
        {
            _M_context._M_captureMethod = _S_captureDeferred;
        }
        else
        {
            _M_context._M_pContextCallback = nullptr;
        }
    }

    // Resolves a context that was created as _S_captureDeferred based on the environment (ancestor, current context).
    void _Resolve(bool _CaptureCurrent)
    {
        if (_M_context._M_captureMethod == _S_captureDeferred)
        {
            _M_context._M_pContextCallback = nullptr;

            if (_CaptureCurrent)
            {
                if (_IsCurrentOriginSTA())
                {
                    _Capture();
                }
#if _UITHREADCTXT_SUPPORT
                else
                {
                    // This method will fail if not called from the UI thread.
                    HRESULT _Hr = CaptureUiThreadContext(&_M_context._M_pContextCallback);
                    if (FAILED(_Hr))
                    {
                        _M_context._M_pContextCallback = nullptr;
                    }
                }
#endif /* _UITHREADCTXT_SUPPORT */
            }
        }
    }

    void _Capture()
    {
        HRESULT _Hr =
            CoGetObjectContext(IID_IContextCallback, reinterpret_cast<void**>(&_M_context._M_pContextCallback));
        if (FAILED(_Hr))
        {
            _M_context._M_pContextCallback = nullptr;
        }
    }

    _ContextCallback(const _ContextCallback& _Src) { _Assign(_Src._M_context._M_pContextCallback); }

    _ContextCallback(_ContextCallback&& _Src)
    {
        _M_context._M_pContextCallback = _Src._M_context._M_pContextCallback;
        _Src._M_context._M_pContextCallback = nullptr;
    }

    _ContextCallback& operator=(const _ContextCallback& _Src)
    {
        if (this != &_Src)
        {
            _Reset();
            _Assign(_Src._M_context._M_pContextCallback);
        }
        return *this;
    }

    _ContextCallback& operator=(_ContextCallback&& _Src)
    {
        if (this != &_Src)
        {
            _M_context._M_pContextCallback = _Src._M_context._M_pContextCallback;
            _Src._M_context._M_pContextCallback = nullptr;
        }
        return *this;
    }

    bool _HasCapturedContext() const
    {
        _ASSERTE(_M_context._M_captureMethod != _S_captureDeferred);
        return (_M_context._M_pContextCallback != nullptr);
    }

    void _CallInContext(_CallbackFunction _Func) const
    {
        if (!_HasCapturedContext())
        {
            _Func();
        }
        else
        {
            ComCallData callData;
            ZeroMemory(&callData, sizeof(callData));
            callData.pUserDefined = reinterpret_cast<void*>(&_Func);

            HRESULT _Hr = _M_context._M_pContextCallback->ContextCallback(
                &_Bridge, &callData, IID_ICallbackWithNoReentrancyToApplicationSTA, 5, nullptr);
            if (FAILED(_Hr))
            {
                throw ::Platform::Exception::CreateException(_Hr);
            }
        }
    }

    bool operator==(const _ContextCallback& _Rhs) const
    {
        return (_M_context._M_pContextCallback == _Rhs._M_context._M_pContextCallback);
    }

    bool operator!=(const _ContextCallback& _Rhs) const { return !(operator==(_Rhs)); }

private:
    void _Reset()
    {
        if (_M_context._M_captureMethod != _S_captureDeferred && _M_context._M_pContextCallback != nullptr)
        {
            _M_context._M_pContextCallback->Release();
        }
    }

    void _Assign(IContextCallback* _PContextCallback)
    {
        _M_context._M_pContextCallback = _PContextCallback;
        if (_M_context._M_captureMethod != _S_captureDeferred && _M_context._M_pContextCallback != nullptr)
        {
            _M_context._M_pContextCallback->AddRef();
        }
    }

    static HRESULT __stdcall _Bridge(ComCallData* _PParam)
    {
        _CallbackFunction* pFunc = reinterpret_cast<_CallbackFunction*>(_PParam->pUserDefined);
        (*pFunc)();
        return S_OK;
    }

    // Returns the origin information for the caller (runtime / Windows Runtime apartment as far as task continuations
    // need know)
    static bool _IsCurrentOriginSTA()
    {
        APTTYPE _AptType;
        APTTYPEQUALIFIER _AptTypeQualifier;

        HRESULT hr = CoGetApartmentType(&_AptType, &_AptTypeQualifier);
        if (SUCCEEDED(hr))
        {
            // We determine the origin of a task continuation by looking at where .then is called, so we can tell
            // whether to need to marshal the continuation back to the originating apartment. If an STA thread is in
            // executing in a neutral apartment when it schedules a continuation, we will not marshal continuations back
            // to the STA, since variables used within a neutral apartment are expected to be apartment neutral.
            switch (_AptType)
            {
                case APTTYPE_MAINSTA:
                case APTTYPE_STA: return true;
                default: break;
            }
        }
        return false;
    }

    union {
        IContextCallback* _M_pContextCallback;
        size_t _M_captureMethod;
    } _M_context;

    static const size_t _S_captureDeferred = 1;
#else  /* defined (__cplusplus_winrt) */
public:
    static _ContextCallback _CaptureCurrent() { return _ContextCallback(); }

    _ContextCallback(bool = false) {}

    _ContextCallback(const _ContextCallback&) {}

    _ContextCallback(_ContextCallback&&) {}

    _ContextCallback& operator=(const _ContextCallback&) { return *this; }

    _ContextCallback& operator=(_ContextCallback&&) { return *this; }

    bool _HasCapturedContext() const { return false; }

    void _Resolve(bool) const {}

    void _CallInContext(_CallbackFunction _Func) const { _Func(); }

    bool operator==(const _ContextCallback&) const { return true; }

    bool operator!=(const _ContextCallback&) const { return false; }

#endif /* defined (__cplusplus_winrt) */
};

template<typename _Type>
struct _ResultHolder
{
    void Set(const _Type& _type) { _Result = _type; }

    _Type Get() { return _Result; }

    _Type _Result;
};

#if defined(__cplusplus_winrt)

template<typename _Type>
struct _ResultHolder<_Type ^>
{
    void Set(_Type ^ const& _type) { _M_Result = _type; }

    _Type ^ Get() { return _M_Result.Get(); } private :
        // ::Platform::Agile handle specialization of all hats
        // including ::Platform::String and ::Platform::Array
        ::Platform::Agile<_Type ^> _M_Result;
};

//
// The below are for composability with tasks auto-created from when_any / when_all / && / || constructs.
//
template<typename _Type>
struct _ResultHolder<std::vector<_Type ^>>
{
    void Set(const std::vector<_Type ^>& _type)
    {
        _Result.reserve(_type.size());

        for (auto _PTask = _type.begin(); _PTask != _type.end(); ++_PTask)
        {
            _Result.emplace_back(*_PTask);
        }
    }

    std::vector<_Type ^> Get()
    {
        // Return vectory<T^> with the objects that are marshaled in the proper apartment
        std::vector<_Type ^> _Return;
        _Return.reserve(_Result.size());

        for (auto _PTask = _Result.begin(); _PTask != _Result.end(); ++_PTask)
        {
            _Return.push_back(
                _PTask->Get()); // Platform::Agile will marshal the object to appropriate apartment if necessary
        }

        return _Return;
    }

    std::vector<::Platform::Agile<_Type ^>> _Result;
};

template<typename _Type>
struct _ResultHolder<std::pair<_Type ^, void*>>
{
    void Set(const std::pair<_Type ^, size_t>& _type) { _M_Result = _type; }

    std::pair<_Type ^, size_t> Get() { return std::make_pair(_M_Result.first.Get(), _M_Result.second); }

private:
    std::pair<::Platform::Agile<_Type ^>, size_t> _M_Result;
};

#endif /* defined (__cplusplus_winrt) */

// An exception thrown by the task body is captured in an exception holder and it is shared with all value based
// continuations rooted at the task. The exception is 'observed' if the user invokes get()/wait() on any of the tasks
// that are sharing this exception holder. If the exception is not observed by the time the internal object owned by the
// shared pointer destructs, the process will fail fast.
struct _ExceptionHolder
{
private:
    void ReportUnhandledError()
    {
#if _MSC_VER >= 1800 && defined(__cplusplus_winrt)
        if (_M_winRTException != nullptr)
        {
            ::Platform::Details::ReportUnhandledError(_M_winRTException);
        }
#endif /* defined (__cplusplus_winrt) */
    }

public:
    explicit _ExceptionHolder(const std::exception_ptr& _E, const _TaskCreationCallstack& _stackTrace)
        : _M_exceptionObserved(0)
        , _M_stdException(_E)
        , _M_stackTrace(_stackTrace)
#if defined(__cplusplus_winrt)
        , _M_winRTException(nullptr)
#endif /* defined (__cplusplus_winrt) */
    {
    }

#if defined(__cplusplus_winrt)
    explicit _ExceptionHolder(::Platform::Exception ^ _E, const _TaskCreationCallstack& _stackTrace)
        : _M_exceptionObserved(0), _M_winRTException(_E), _M_stackTrace(_stackTrace)
    {
    }
#endif /* defined (__cplusplus_winrt) */

    __declspec(noinline) ~_ExceptionHolder()
    {
        if (_M_exceptionObserved == 0)
        {
            // If you are trapped here, it means an exception thrown in task chain didn't get handled.
            // Please add task-based continuation to handle all exceptions coming from tasks.
            // this->_M_stackTrace keeps the creation callstack of the task generates this exception.
            _REPORT_PPLTASK_UNOBSERVED_EXCEPTION();
        }
    }

    void _RethrowUserException()
    {
        if (_M_exceptionObserved == 0)
        {
            atomic_exchange(_M_exceptionObserved, 1l);
        }

#if defined(__cplusplus_winrt)
        if (_M_winRTException != nullptr)
        {
            throw _M_winRTException;
        }
#endif /* defined (__cplusplus_winrt) */
        std::rethrow_exception(_M_stdException);
    }

    // A variable that remembers if this exception was every rethrown into user code (and hence handled by the user).
    // Exceptions that are unobserved when the exception holder is destructed will terminate the process.
    atomic_long _M_exceptionObserved;

    // Either _M_stdException or _M_winRTException is populated based on the type of exception encountered.
    std::exception_ptr _M_stdException;
#if defined(__cplusplus_winrt)
    ::Platform::Exception ^ _M_winRTException;
#endif /* defined (__cplusplus_winrt) */

    // Disassembling this value will point to a source instruction right after a call instruction. If the call is to
    // create_task, a task constructor or the then method, the task created by that method is the one that encountered
    // this exception. If the call is to task_completion_event::set_exception, the set_exception method was the source
    // of the exception. DO NOT REMOVE THIS VARIABLE. It is extremely helpful for debugging.
    _TaskCreationCallstack _M_stackTrace;
};

#if defined(__cplusplus_winrt)
/// <summary>
///     Base converter class for converting asynchronous interfaces to IAsyncOperation
/// </summary>
template<typename _AsyncOperationType, typename _CompletionHandlerType, typename _Result>
ref struct _AsyncInfoImpl abstract : Windows::Foundation::IAsyncOperation<_Result>
{
    internal :
        // The async action, action with progress or operation with progress that this stub forwards to.
        ::Platform::Agile<_AsyncOperationType>
            _M_asyncInfo;

For faster browsing, not all history is shown. View entire blame