Code: Select all
Mutex mutex = new();
BankAccount account = new();
var task = Task.Run(() =>
{
bool locked = false;
try
{
locked = mutex.WaitOne();
if (locked) account.Deposit(100);
}
finally
{
// if (locked) mutex.ReleaseMutex();
}
});
task.Wait();
try
{
_ = mutex.WaitOne(); // it waits here forever
}
catch (AbandonedMutexException)
{
Console.WriteLine($"{nameof(AbandonedMutexException)} was thrown");
}
public class BankAccount
{
public int Balance { get; private set; }
public void Deposit(int amount) => Balance += amount;
public void Withdraw(int amount) => Balance -= amount;
}
Mutex mutex = new();
BankAccount account = new();
new Thread(() =>
{
bool locked = false;
try
{
locked = mutex.WaitOne();
if (locked) account.Deposit(100);
}
finally
{
// if (locked) mutex.ReleaseMutex();
}
}).Start();
Thread.Sleep(1000);
try
{
_ = mutex.WaitOne();
}
catch (AbandonedMutexException)
{
// caught successfully
Console.WriteLine($"{nameof(AbandonedMutexException)} was thrown");
}
< /code>
Was verursacht ein solcher Unterschied? Ist die Aufgabe nicht ein Wrapper für Thread?