2009-05-28 13 views

risposta

10

C'è Interlocked.Exchange. Questo lo fa in una chiamata atomica thread-safe.


Edit dopo i commenti:

Giusto per chiarire come funziona utilizzando Interlocked.Exchange, fareste:

left = Interlocked.Exchange(ref right, left); 

Questo sarà l'equivalente (in effetti) per fare:

Swap(ref left, ref right); 

Tuttavia, Interlocked.Exchange esegue questa operazione come un'operazione atomica, quindi è a prova di thread.

+1

Interlocked.Exchange imposta un valore, in realtà non scambia valori. Dovresti comunque salvare una temperatura e chiamare due volte Interlocked.Exchange, in modo da non ottenere alcun guadagno. – jrista

+1

Interlocked.Exchange non è realmente equivalente allo Swap specificato. Cambia solo il primo valore e non tocca il secondo (stesso). –

+1

@Mehdrad: left = InterlockedExchange (ref right, left); –

3

No, il framework non ha un tale metodo. Probabilmente il motivo è che non c'è molto vantaggio nell'integrarlo e potresti facilmente (come hai fatto tu) aggiungerlo tu stesso. Ciò richiede anche l'uso di ref come parametro, che limiterà notevolmente i casi d'uso. Ad esempio, non è possibile eseguire questa operazione:

List<int> test; 
// ... 
Swap(ref test[0], ref test[1]); // won't work, it's an indexer, not an array 
Problemi correlati