C#中:我怎样才能让一个IEnumerable< T>线程安全的? [英] C#: How can I make an IEnumerable<T> thread safe?

查看:119
本文介绍了C#中:我怎样才能让一个IEnumerable< T>线程安全的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有这个简单的方法:

Say I have this simple method:

public IEnumerable<uint> GetNumbers()
{
    uint n = 0;
    while(n < 100)
        yield return n++;
}



你将如何让这个线程安全的?而我的意思是,你会得到枚举一次,并有多个线程处理所有的数字没有任何人得到重复。

How would you make this thread safe? And by that I mean that you would get that enumerator once, and have multiple threads handle all the numbers without anyone getting duplicates.

我想一个锁需要在某处使用,但如果必须在该锁是一个迭代器块是线程安全的?什么,一般来说,你需要记住,如果你想有一个线程安全的的IEnumerable< T> ?或者更确切地说,我想这会是一个线程安全的的IEnumerator< T> ...

I suppose a lock needs to be used somewhere, but where must that lock be for an iterator block to be thread safe? What, in general, do you need to remember if you want a thread safe IEnumerable<T>? Or rather I guess it would be a thread safe IEnumerator<T>...?

推荐答案

有这样做的一个固有的问题,因为的IEnumerator< T> 同时具有的MoveNext()电流。你真的想要一个调用,如:

There's an inherent problem in doing so, because IEnumerator<T> has both MoveNext() and Current. You really want a single call such as:

bool TryMoveNext(out T value)

在这一点上,你可以的原子的移动到下一个元素,并得到一个值。实现这一点,仍然能够使用收益可能会非常棘手。我将有一个想一想虽然。我想你需要包装非线程安全的迭代器,其中中自动执行的MoveNext()当前来实现上面所示的界面。我不知道你怎么会那么包装这个接口回的IEnumerator< T> ,这样你可以在的foreach 虽然...

at that point you can atomically move to the next element and get a value. Implementing that and still being able to use yield could be tricky... I'll have a think about it though. I think you'd need to wrap the "non-threadsafe" iterator in a thread-safe one which atomically performed MoveNext() and Current to implement the interface shown above. I don't know how you'd then wrap this interface back into IEnumerator<T> so that you could use it in foreach though...

如果您正在使用.NET 4.0,并行扩展的可能的能够帮助你 - 你会。需要解释一下你想要虽然做什么

If you're using .NET 4.0, Parallel Extensions may be able to help you - you'd need to explain more about what you're trying to do though.

这是一个有趣的话题 - 我可能要在博客吧...

This is an interesting topic - I may have to blog about it...

编辑:我现在已经博客上讲述它的方法有两种。

I've now blogged about it with two approaches.

这篇关于C#中:我怎样才能让一个IEnumerable&LT; T&GT;线程安全的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆