C# 阻止一段代码被多次调用的最佳解决方案?
我有一个每1小时调用一次的方法。但有时方法操作没有在一小时内完全完成,并且再次调用该方法,这会导致混乱。因此,我必须找出前面的方法是否已经完成。解决这个问题的最好办法是什么C# 阻止一段代码被多次调用的最佳解决方案?,c#,C#,我有一个每1小时调用一次的方法。但有时方法操作没有在一小时内完全完成,并且再次调用该方法,这会导致混乱。因此,我必须找出前面的方法是否已经完成。解决这个问题的最好办法是什么 // will be called for every one hour where the value will be repeated // At sometimes it is possible for the same value to be called continually for the next
// will be called for every one hour where the value will be repeated
// At sometimes it is possible for the same value to be called continually
for the next hour and at that time problem occurs
Void Method(int value)
{
If(value =0)
// Do some operations which may exceed one hour
Else If(value =1)
// Do some operation’s which may exceed one hour
.
.
.
}
谢谢,一个问题是,如果在方法仍在运行时调用该方法,您希望发生什么 此代码将删除第二个呼叫
private bool _running = false;
private readonly object _lock = new object();
void Method(int value)
{
lock (_lock)
{
if (_running)
{
return;
}
else
{
_running = true;
}
}
if (value == 0)
{
// Do some operations which may exceed one hour
}
else if (value == 1)
{
// Do some operation’s which may exceed one hour
}
_running = false;
}
一个简单的想法是将状态保存在类字段中,以便该方法检查是否可以自由地执行某些工作。这意味着,如果您调用了该方法,而该方法正忙,那么您的调用将无法进行工作:
private static bool methodIsBusy = false;
private static void WaitAndWriteMessage(TimeSpan waitTime, string message)
{
// If we're busy, return right away
if (methodIsBusy) return;
// Let future calls know we're busy
methodIsBusy = true;
Thread.Sleep(waitTime);
Console.Write($"Method ran at: {DateTime.Now.ToString("hh:mm:ss")}. ");
Console.WriteLine(message);
// Allow future calls to run now
methodIsBusy = false;
}
我们的测试方法:
private static void Main()
{
for(int i = 0; i < 3; i++)
{
Task.Run(() => WaitAndWriteMessage(TimeSpan.FromSeconds(5),
$"Method called at {DateTime.Now.ToString("hh:mm:ss")}."));
Thread.Sleep(1000);
}
Console.ReadKey();
GetKeyFromUser("\nDone!\nPress any key to exit...");
}
我们的测试方法是:
private static void Main()
{
for(int i = 0; i < 3; i++)
{
Task.Run(() => WaitAndWriteMessage(TimeSpan.FromSeconds(5),
$"Method called at {DateTime.Now.ToString("hh:mm:ss")}."));
Thread.Sleep(1000);
}
Console.ReadKey();
}
private static void Main()
{
对于(int i=0;i<3;i++)
{
Task.Run(()=>WaitAndWriteMessage(TimeSpan.FromSeconds(5)),
$”方法在{DateTime.Now.ToString(“hh:mm:ss”)}调用;
睡眠(1000);
}
Console.ReadKey();
}
输出
(注意调用消息的时间和执行消息的时间之间的差异每次都会变长)
如何调用此方法?你的帖子中没有任何有用的代码来回答你的问题。请发布一个。方法被每一小时运行一次的线程调用。
private static void Main()
{
for(int i = 0; i < 3; i++)
{
Task.Run(() => WaitAndWriteMessage(TimeSpan.FromSeconds(5),
$"Method called at {DateTime.Now.ToString("hh:mm:ss")}."));
Thread.Sleep(1000);
}
Console.ReadKey();
}