C# 如何使用Concur一次在一台机器上执行同步任务?

C# 如何使用Concur一次在一台机器上执行同步任务?,c#,locking,consul,consul-kv,leader-election,C#,Locking,Consul,Consul Kv,Leader Election,我有一个10台机器的系统,我需要在每台机器上以同步顺序逐个执行特定任务。基本上,在特定时间只有一台机器可以完成该任务。我们已经使用了concur用于其他目的,但我在想我们是否也可以使用concur来实现这一点 我读到了更多关于它的信息,看起来我们可以使用领导者选举和执政官选举,每台机器将尝试获取锁,完成工作,然后释放锁。一旦工作完成,它将释放锁,然后其他机器将再次尝试获取锁并执行相同的工作。这样一来,每件事情都将一次同步到一台机器上 我决定使用这个C#PlayFab-consultdotnet,

我有一个10台机器的系统,我需要在每台机器上以同步顺序逐个执行特定任务。基本上,在特定时间只有一台机器可以完成该任务。我们已经使用了
concur
用于其他目的,但我在想我们是否也可以使用
concur
来实现这一点

我读到了更多关于它的信息,看起来我们可以使用领导者选举和执政官选举,每台机器将尝试获取锁,完成工作,然后释放锁。一旦工作完成,它将释放锁,然后其他机器将再次尝试获取锁并执行相同的工作。这样一来,每件事情都将一次同步到一台机器上

我决定使用这个
C#
PlayFab-consultdotnet
,它已经内置了这个功能,看起来像是这样,但是如果有更好的选择,我也愿意接受。下面的
Action
方法在我的代码库中几乎通过一个观察机制在每台机器上同时调用

 private void Action() {
    // Try to acquire lock using Consul.
    // If lock acquired then DoTheWork() otherwise keep waiting for it until lock is acquired.
    // Once work is done, release the lock
    // so that some other machine can acquire the lock and do the same work.
 }
现在,在上面的方法中,我需要做下面的事情-

  • 尝试获取锁。如果您无法获得锁,请等待,因为其他机器可能会在您之前抢走它
  • 如果已获取锁,则DoTheWork()
  • 工作完成后,松开锁,以便其他机器可以获得锁并执行相同的工作
想法是所有10台机器都应该
DoTheWork()
一次同步一台。基于这一点,我决定修改他们的例子,以适应我们的需要-

以下是我的
LeaderElectionService
课程:

public class LeaderElectionService
{
    public LeaderElectionService(string leadershipLockKey)
    {
        this.key = leadershipLockKey;
    }

    public event EventHandler<LeaderChangedEventArgs> LeaderChanged;
    string key;
    CancellationTokenSource cts = new CancellationTokenSource();
    Timer timer;
    bool lastIsHeld = false;
    IDistributedLock distributedLock;

    public void Start()
    {
        timer = new Timer(async (object state) => await TryAcquireLock((CancellationToken)state), cts.Token, 0, Timeout.Infinite);
    }

    private async Task TryAcquireLock(CancellationToken token)
    {
        if (token.IsCancellationRequested)
            return;
        try
        {
            if (distributedLock == null)
            {
                var clientConfig = new ConsulClientConfiguration { Address = new Uri("http://consul.host.domain.com") };
                ConsulClient client = new ConsulClient(clientConfig);
                distributedLock = await client.AcquireLock(new LockOptions(key) { LockTryOnce = true, LockWaitTime = TimeSpan.FromSeconds(3) }, token).ConfigureAwait(false);
            }
            else
            {
                if (!distributedLock.IsHeld)
                {
                    await distributedLock.Acquire(token).ConfigureAwait(false);
                }
            }
        }
        catch (LockMaxAttemptsReachedException ex)
        {
            //this is expected if it couldn't acquire the lock within the first attempt.
            Console.WriteLine(ex.Stacktrace);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Stacktrace);
        }
        finally
        {
            bool lockHeld = distributedLock?.IsHeld == true;
            HandleLockStatusChange(lockHeld);
            //Retrigger the timer after a 10 seconds delay (in this example). Delay for 7s if not held as the AcquireLock call will block for ~3s in every failed attempt.
            timer.Change(lockHeld ? 10000 : 7000, Timeout.Infinite);
        }
    }

    protected virtual void HandleLockStatusChange(bool isHeldNew)
    {
        // Is this the right way to check and do the work here?
        // In general I want to call method "DoTheWork" in "Action" method itself
        // And then release and destroy the session once work is done.
        if (isHeldNew)
        {
            // DoTheWork();
            Console.WriteLine("Hello");
            // And then were should I release the lock so that other machine can try to grab it?
            // distributedLock.Release();
            // distributedLock.Destroy();
        }

        if (lastIsHeld == isHeldNew)
            return;
        else
        {
            lastIsHeld = isHeldNew;
        }

        if (LeaderChanged != null)
        {
            LeaderChangedEventArgs args = new LeaderChangedEventArgs(lastIsHeld);
            foreach (EventHandler<LeaderChangedEventArgs> handler in LeaderChanged.GetInvocationList())
            {
                try
                {
                    handler(this, args);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Stacktrace);
                }
            }
        }
    }
}
public class LeaderChangedEventArgs : EventArgs
{
    private bool isLeader;

    public LeaderChangedEventArgs(bool isHeld)
    {
        isLeader = isHeld;
    }

    public bool IsLeader { get { return isLeader; } }
}
在上面的代码中,我的用例可能不需要很多片段,但想法是一样的

问题陈述

现在在我的
Action
方法中,我想使用上面的类,并在获得锁后立即执行任务,否则继续等待锁。工作完成后,释放并销毁会话,以便其他机器可以抓住它并执行工作。在我下面的方法中,我对如何正确使用上面的类有点困惑

 private void Action() {
    LeaderElectionService electionService = new LeaderElectionService("data/process");
    // electionService.LeaderChanged += (source, arguments) => Console.WriteLine(arguments.IsLeader ? "Leader" : "Slave");
    electionService.Start();

    // now how do I wait for the lock to be acquired here indefinitely
    // And once lock is acquired, do the work and then release and destroy the session
    // so that other machine can grab the lock and do the work
 }
我最近开始使用
C 35;
,这就是为什么对于如何通过使用
concur
和这个库在生产中高效地工作有点困惑

更新

根据您的建议,我尝试了下面的代码,我想我之前也尝试过,但由于某种原因,当它转到这一行时,
等待distributedLock.Acquire(cancellationToken),它只是自动返回到主方法。它从不前进到我的
做一些工作打印输出。
CreateLock
实际工作吗?我希望它会在concur上创建
数据/锁
(因为它不在那里),然后尝试获取它的锁,如果获取了锁,则执行该工作,然后为其他机器释放它

private static CancellationTokenSource cts = new CancellationTokenSource();

public static void Main(string[] args)
{
    Action(cts.Token);
    Console.WriteLine("Hello World");
}

private static async Task Action(CancellationToken cancellationToken)
{
    const string keyName = "data/lock";

    var clientConfig = new ConsulClientConfiguration { Address = new Uri("http://consul.test.host.com") };
    ConsulClient client = new ConsulClient(clientConfig);
    var distributedLock = client.CreateLock(keyName);

    while (true)
    {
        try
        {
            // Try to acquire lock
            // As soon as it comes to this line,
            // it just goes back to main method automatically. not sure why
            await distributedLock.Acquire(cancellationToken);

            // Lock is acquired
            // DoTheWork();
            Console.WriteLine("Doing Some Work!");

            // Work is done. Jump out of loop to release the lock
            break;
        }
        catch (LockHeldException)
        {
            // Cannot acquire the lock. Wait a while then retry
            await Task.Delay(TimeSpan.FromSeconds(10), cancellationToken);
        }
        catch (Exception)
        {
            // TODO: Handle exception thrown by DoTheWork method

            // Here we jump out of the loop to release the lock
            // But you can try to acquire the lock again based on your requirements
            break;
        }
    }

    // Release and destroy the lock
    // So that other machine can grab the lock and do the work
    await distributedLock.Release(cancellationToken);
    await distributedLock.Destroy(cancellationToken);
}

依我看,在你的情况下,来自那些博客的
leaderlectionservice
是一种过火的行为

更新1

无需在循环时执行
,因为:

  • consultclient
    是局部变量
    • 无需检查
      IsHeld
      属性
  • Acquire
    将无限期阻止,除非
    • LockOptions
    • 将超时设置为
      CancellationToken
  • 旁注,在分布式锁()上调用
    Release
    后,不必调用
    Destroy
    方法

    更新2

    OP的代码返回到
    Main
    方法的原因是,
    Action
    方法没有等待。如果使用C#7.1并将
    wait
    置于
    Action
    方法上,则可以使用

    public static async Task Main(string[] args)
    {
        await Action(cts.Token);
        Console.WriteLine("Hello World");
    }
    

    谢谢你的建议。我用我已经详细尝试过的内容更新了我的问题。除非我做错了什么事,否则这不起作用。有什么想法?原因是什么?有什么想法吗@HanZhao@user1950349-更新帖子。请检查一下,如果你有任何问题,请告诉我。对不起,回复太晚了。当然,让我再彻底测试一遍。谢谢你的帮助!关于这一点,我有一个简短的问题。假设相同的代码在10多台机器上运行。他们都会尝试运行这一行
    client.CreateLock(keyName)public static async Task Main(string[] args)
    {
        await Action(cts.Token);
        Console.WriteLine("Hello World");
    }