Skip to content

Instantly share code, notes, and snippets.

@hythof
Last active April 21, 2017 07:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hythof/449ffe81cd8f124c8950 to your computer and use it in GitHub Desktop.
Save hythof/449ffe81cd8f124c8950 to your computer and use it in GitHub Desktop.
マルチスレッドで高速なC#を書くためのロック戦略 ref: http://qiita.com/tadokoro/items/28b3623a5ec58517d431
int incrementedValue = Interlocked.Increment(ref intValue); // 安全にインクリメント
class X {
object lockObject = new object();
public void Work() {
lock(lockObject) {
// ロックの中
}
}
}
class X {
SemaphoreSlim sem = new SemaphoreSlim(1, 1);
public async Task Work() {
await sem.WaitAsync().ConfigureAwait(false);
try {
// ロックの中、awaitもok
} finally {
sem.Release();
}
}
}
class X {
Semaphore sem = new Semaphore(1, 1);
public void Work() {
sem.WaitOne();
try {
// ロックの中、awaitもok
} finally {
sem.Release();
}
}
}
class X {
Mutex mut = new Mutex();
public void Work() {
mut.WaitOne();
try {
// ロックの中
} finally {
mut.ReleaseMutex();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment