- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
与this question相关,
是await
应该恢复 Thread.CurrentContext
的上下文(特别是 ContextBoundObject
表示的上下文) ?考虑以下内容:
class Program
{
static void Main(string[] args)
{
var c1 = new Class1();
Console.WriteLine("Method1");
var t = c1.Method1();
t.Wait();
Console.WriteLine("Method2");
var t2 = c1.Method2();
t2.Wait();
Console.ReadKey();
}
}
public class MyAttribute : ContextAttribute
{
public MyAttribute() : base("My") { }
}
[My]
public class Class1 : ContextBoundObject
{
private string s { get { return "Context: {0}"; } } // using a property here, since using a field causes things to blow-up.
public async Task Method1()
{
Console.WriteLine(s, Thread.CurrentContext.ContextID); // Context1
await Task.Delay(50);
Console.WriteLine(s, Thread.CurrentContext.ContextID); // Context0
}
public Task Method2()
{
Console.WriteLine(s, Thread.CurrentContext.ContextID); // Context1
return Task.Delay(50).ContinueWith(t => Console.WriteLine(s, Thread.CurrentContext.ContextID)); // Context1
}
}
在async
/await
在这种情况下,上下文不会恢复,因此 await 之后的剩余代码最终会在不同的上下文中执行。
在.ContinueWith
在这种情况下,上下文不会被 tpl 恢复,而是由于 lambda 最终被转入类成员方法这一事实,上下文最终得到恢复。如果 lambda 不使用成员变量,在这种情况下也不会恢复上下文。
似乎正因为如此,使用async
/await
或 ContextBoundObject
的延续s 会导致意想不到的行为。例如,考虑一下我们是否使用了 [Synchronization]
使用 async
的类的属性 ( MSDN doc)/await
.同步保证不适用于第一个 await
之后的代码.
回应@Noseratio
ContextBoundObjects
不要(必须或默认情况下)需要线程关联。在这个例子中,我给出了上下文最终相同的地方,你最终不会在同一个线程上(除非你很幸运)。您可以使用 Context.DoCallBack(...)
在上下文中工作。这不会让您进入原始线程(除非 Context
为您完成)。这是对 Class1
的修改证明:
public async Task Method1()
{
var currCtx = Thread.CurrentContext;
Console.WriteLine(s, currCtx.ContextID); // Context1
Console.WriteLine("Thread Id: {0}", Thread.CurrentThread.ManagedThreadId);
await Task.Delay(50);
currCtx.DoCallBack(Callback);
}
static void Callback()
{
Console.WriteLine("Context: {0}", Thread.CurrentContext.ContextID); // Context1
Console.WriteLine("Thread Id: {0}", Thread.CurrentThread.ManagedThreadId);
}
如果await
如果要恢复上下文,我的期望是上下文不会被“复制”到新线程,而是类似于 SynchronizationContext
的方式。被恢复。基本上,您希望在 await
处捕获当前上下文。 ,然后您希望通过调用 capturedContext.DoCallback(afterAwaitWork)
来执行 await 之后的部分。 .
DoCallback
做恢复上下文的工作。具体恢复上下文的工作是什么取决于具体的上下文。
基于此,似乎可能可以通过创建自定义 SynchronizationContext
来实现此行为。它包装了在调用 DoCallback
时发布给它的任何工作.
最佳答案
显然,Thread.CurrentContext
没有流动。有趣的是,作为 ExecutionContext
的一部分,实际得到了什么流,here in .NET reference sources .特别有趣的是,同步上下文如何通过 ExecutionContext.Run
显式流动,而不是通过 Task.Run
隐式流动。
我不确定自定义的同步上下文(例如 AspNetSynchronizationContext
),它可能比 ExecutionContext
默认情况下传递更多的线程属性。
这是一篇很棒的相关读物:"ExecutionContext vs SynchronizationContext" .
已更新,Thread.CurrentContext
似乎根本无法流动,即使 如果您想这样做手动(使用 Stephen Toub 的 WithCurrentCulture
之类的东西)。检查 System.Runtime.Remoting.Contexts.Context
的执行情况,显然它不是为复制到另一个线程而设计的(与 SynchronizationContext
或 ExecutionContext
不同)。
我不是 .NET 远程处理方面的专家,但我认为 ContextBoundObject
派生的对象需要线程关联。即,它们在其生命周期内在同一个线程上创建、访问和销毁。我相信这是 ContextBoundObject
设计要求的一部分。
更新,基于@MattSmith 的更新。
Matt,您说得对,当从不同的域调用时,基于 ContextBoundObject
的对象没有线程关联。如果在类上指定了 [Synchronization]
,则跨不同线程或上下文对整个对象的访问将被序列化。
据我所知,线程和上下文之间也没有逻辑联系。上下文是与对象关联的事物。可以有多个上下文在同一个线程上运行(与 COM 单元不同),并且多个线程共享同一个上下文(类似于 COM 单元)。
使用 Context.DoCallback
,确实可以在 await
之后继续相同的上下文,或者使用自定义等待程序(如以下代码中所做的),或者正如您在问题中提到的,具有自定义同步上下文。
我玩过的代码:
using System;
using System.Runtime.Remoting.Contexts;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication
{
public class Program
{
[Synchronization]
public class MyController: ContextBoundObject
{
/// All access to objects of this type will be intercepted
/// and a check will be performed that no other threads
/// are currently in this object's synchronization domain.
int i = 0;
public void Test()
{
Console.WriteLine(String.Format("\nenter Test, i: {0}, context: {1}, thread: {2}, domain: {3}",
this.i,
Thread.CurrentContext.ContextID,
Thread.CurrentThread.ManagedThreadId,
System.AppDomain.CurrentDomain.FriendlyName));
Console.WriteLine("Testing context...");
Program.TestContext();
Thread.Sleep(1000);
Console.WriteLine("exit Test");
this.i++;
}
public async Task TaskAsync()
{
var context = Thread.CurrentContext;
var contextAwaiter = new ContextAwaiter();
Console.WriteLine(String.Format("TaskAsync, context: {0}, same context: {1}, thread: {2}",
Thread.CurrentContext.ContextID,
Thread.CurrentContext == context,
Thread.CurrentThread.ManagedThreadId));
await Task.Delay(1000);
Console.WriteLine(String.Format("after Task.Delay, context: {0}, same context: {1}, thread: {2}",
Thread.CurrentContext.ContextID,
Thread.CurrentContext == context,
Thread.CurrentThread.ManagedThreadId));
await contextAwaiter;
Console.WriteLine(String.Format("after await contextAwaiter, context: {0}, same context: {1}, thread: {2}",
Thread.CurrentContext.ContextID,
Thread.CurrentContext == context,
Thread.CurrentThread.ManagedThreadId));
}
}
// ContextAwaiter
public class ContextAwaiter :
System.Runtime.CompilerServices.INotifyCompletion
{
Context _context;
public ContextAwaiter()
{
_context = Thread.CurrentContext;
}
public ContextAwaiter GetAwaiter()
{
return this;
}
public bool IsCompleted
{
get { return false; }
}
public void GetResult()
{
}
// INotifyCompletion
public void OnCompleted(Action continuation)
{
_context.DoCallBack(() => continuation());
}
}
// Main
public static void Main(string[] args)
{
var ob = new MyController();
Action<string> newDomainAction = (name) =>
{
System.AppDomain domain = System.AppDomain.CreateDomain(name);
domain.SetData("ob", ob);
domain.DoCallBack(DomainCallback);
};
Console.WriteLine("\nPress Enter to test domains...");
Console.ReadLine();
var task1 = Task.Run(() => newDomainAction("domain1"));
var task2 = Task.Run(() => newDomainAction("domain2"));
Task.WaitAll(task1, task2);
Console.WriteLine("\nPress Enter to test ob.Test...");
Console.ReadLine();
ob.Test();
Console.WriteLine("\nPress Enter to test ob2.TestAsync...");
Console.ReadLine();
var ob2 = new MyController();
ob2.TaskAsync().Wait();
Console.WriteLine("\nPress Enter to test TestContext...");
Console.ReadLine();
TestContext();
Console.WriteLine("\nPress Enter to exit...");
Console.ReadLine();
}
static void DomainCallback()
{
Console.WriteLine(String.Format("\nDomainCallback, context: {0}, thread: {1}, domain: {2}",
Thread.CurrentContext.ContextID,
Thread.CurrentThread.ManagedThreadId,
System.AppDomain.CurrentDomain.FriendlyName));
var ob = (MyController)System.AppDomain.CurrentDomain.GetData("ob");
ob.Test();
Thread.Sleep(1000);
}
public static void TestContext()
{
var context = Thread.CurrentContext;
ThreadPool.QueueUserWorkItem(_ =>
{
Console.WriteLine(String.Format("QueueUserWorkItem, context: {0}, same context: {1}, thread: {2}",
Thread.CurrentContext.ContextID,
Thread.CurrentContext == context,
Thread.CurrentThread.ManagedThreadId));
}, null);
ThreadPool.UnsafeQueueUserWorkItem(_ =>
{
Console.WriteLine(String.Format("UnsafeQueueUserWorkItem, context: {0}, same context: {1}, thread: {2}",
Thread.CurrentContext.ContextID,
Thread.CurrentContext == context,
Thread.CurrentThread.ManagedThreadId));
}, null);
}
}
}
关于c# - 等待应该恢复 Thread.CurrentContext 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22416182/
完成此任务的最佳方法是什么:主线程(线程 A)创建另外两个线程(线程 B 和线程 C)。线程 B 和 C 执行繁重的磁盘 I/O,最终需要将它们创建的资源传递给线程 A,然后调用外部 DLL 文件中的
我是一名对 Julia 语言感兴趣的新手程序员。文档( https://docs.julialang.org/en/v1/base/multi-threading/ )说 Threads.@threa
python中的thread.start_new_thread和threading.Thread.start有什么区别? 我注意到,当调用 start_new_thread 时,新线程会在调用线程终止
我正在学习安卓蓝牙编程。我从 Google 的 Android 开发者网站上复制了大部分代码以供学习。这个想法是监听服务器上的连接是在一个新线程中完成的,而不会阻塞 UI 线程。当收到连接请求时,连接
执行对象方法的线程是否依赖于创建它的线程上的线程? 假设您的 java 应用程序中有两个线程 Thread1 和 Thread2,以及两个类 ClassA 和 ClassB。 您在 Thread1 上
我正在用这段代码测试 C++11 线程,但是在创建线程时,我遇到了错误没有匹配函数调用 'std::thread::thread()'. 这就像我给 std::thread ctr 的函数有什么问题,
我有如下类 eventEngine 和网关: class eventEngine { public: eventEngine(); std::thread threa; std
我需要运行与列表 dirlist 中的元素一样多的 Observer 类线程。当我运行它 python 控制台时,它可以正常工作。 class Observer(Thread): def ru
我在一本 Java 书中读到了下面的代码。我知道主类默认继承 Thread 类,所以 currentThread();而不是 Thread.currentThread();也会做这项工作。 但我不明白
我在我的系统中使用第 3 方 API,该 API 启动一个永久运行的用户线程。一旦我的程序结束,JVM 由于该线程而继续运行,因此我尝试获取此线程引用并通过更改它 thread.setDaemon(t
我所知道的 Python 中的每个对象都可以通过调用来处理其基类初始化: super(BaseClass, self).__init__() threading.Thread 的子类似乎不是这种情况,
在我最近从事的 Xamarin 项目中,我可以看到开发人员使用了 Java.Lang.Thread 以及 System.Threading.Thread(用于非常相似的操作 - 例如在后台加载数据)。
我在 Julia 中运行双循环。代码非常简单。 w = rand(1000,1000) function regular_demo(w::Array{Float64, 2}) n = size
我在 Windows 上使用 Python 3。我正在使用 threading.Thread动态运行一个函数,我可以带参数或不带参数调用它。我正在设置一个列表,其中的第一项是定义路径的字符串。其他参数
我遇到了一些使用线程模块(使用 Python 2.6)管理线程的示例。 我想了解的是这个例子是如何调用“运行”方法的,在哪里调用的。我在任何地方都看不到它。 ThreadUrl 类在 main() 函
假设我从 threading.Thread 派生: from threading import Thread class Worker(Thread): def start(self):
关闭。这个问题需要debugging details .它目前不接受答案。 编辑问题以包含 desired behavior, a specific problem or error, and th
使用 WinDbg 和 SOS,我有以下内容: 0:011> !threads ThreadCount: 7 UnstartedThread: 0 BackgroundThread: 4 Pendin
App Engine 给出错误: com.google.apphosting.api.ApiProxy$CallNotFoundException: Can't make API call urlfe
我正在尝试将 Swing JEditorPane 嵌入到 JavaFX 项目中,如下代码所示。 Platform.runLater(() -> { SyntaxTester ob = new
我是一名优秀的程序员,十分优秀!