小编Ala*_*tge的帖子

WinRT上下文中与Async的线程关联

我想使用ThreadStatic的现有代码来实现每个线程的单例(如Transaction.Current)

但是,它不适用于在新任务中运行的async/await模型.我知道,由于SynchronizationContext.Current为null,因此使用ThreadPoolTask​​Scheduler,并且continuation可以在另一个线程中.

例如,如果我执行以下代码:

Task.Factory.StartNew(async () =>
{                    
   Debug.WriteLine("Start on thread {0}", Environment.CurrentManagedThreadId);
   await Task.Delay(10);
   Debug.WriteLine("Continue on thread {0}", Environment.CurrentManagedThreadId);
});
Run Code Online (Sandbox Code Playgroud)

结果是:

从线程5开始

继续第4个主题

我的单例实现是这样的:

[ThreadStatic]
private static long? _sessionIndex; // Immutable value
private static ConcurrentDictionary<long, ...> contexts;
public static ... Current 
{
  get { 
    return contexts[_sessionIndex ?? (_sessionIndex=Interlocked.Increment(..))];
  }
}
Run Code Online (Sandbox Code Playgroud)

Stephen Cleary提出了另一种基于"每个ExecutionContext的单例"的解决方案,它在4.5.1上下文中完美运行但不适用于有限的winrt平台(CallContext不存在)

作为一个解决方案,我会尝试在与主任务相同的线程中强制继续执行,以保持ThreadStatic机制.

实现TaskScheduler可能是一个解决方案,但你不能在winrt中操纵线程.

也许使用特定的SynchronizationContext但我没有找到如何.我担心这是不可能的.

任何的想法 ?

c# asynchronous async-await winrt-async

3
推荐指数
1
解决办法
419
查看次数

标签 统计

async-await ×1

asynchronous ×1

c# ×1

winrt-async ×1