如何处理ThreadPool和成员变量?
我对 .NET 中的 ThreadPool 有点陌生。 我想知道,如果我只能将一个对象发送到我的回调方法,我如何才能访问类成员变量来调用其方法? (请参阅 CallBack() 中的 customClass)
我将如何从 customClass 加载数据? 我是否将 customClass 传递给不同的 CallBack 方法? 这种方法可以吗?
正如您所看到的,这有点缺乏经验,因此我们将不胜感激。
谢谢你, 卡韦
class Program
{
static void Main(string[] args)
{
CustomClass customClass = new CustomClass();
ThreadPool.QueueUserWorkItem(CallBack, "Hello");
Console.Read();
}
private static void CallBack(object state)
{
customClass.SaveData(state.ToString());
}
}
I am a bit new to ThreadPool in .NET. I was wondering, if I can only send one object to my callback method, how am I able to access the class member variable to call its methods? (see customClass in CallBack())
And how would I load the data from customClass? Do I pass the customClass to a different CallBack method? is this approach alright?
As you can see it is a bit of lack of experience, so any tips along the way would really be appreciated.
Thank you,
Kave
class Program
{
static void Main(string[] args)
{
CustomClass customClass = new CustomClass();
ThreadPool.QueueUserWorkItem(CallBack, "Hello");
Console.Read();
}
private static void CallBack(object state)
{
customClass.SaveData(state.ToString());
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
最简单的方法是使用 闭包 捕获您想要的所有变量(即使用匿名方法或 lambda 表达式)。 如果使用循环,则需要小心捕获的确切内容,但它比传递对象并必须将其强制转换回正确的类型等更方便。
The easiest way to do this is to use a closure to capture all the variables you want (i.e. use an anonymous method or a lambda expression). You need to be careful about exactly what's captured if you're using a loop, but it's handier than passing through an object and having to cast it back to the right type etc.
除了已经说过的内容之外:如果
CustomClass
在您的控制之下并且异步调用SaveData
是常见用例,您可以考虑提供SaveDataAsync 方法:
请参阅基于事件的异步模式。
In addition to what has been said: If
CustomClass
is under your control and asynchronously invokingSaveData
is a common use case, you could think about providing aSaveDataAsync
method:See the Event-based Asynchronous Pattern.