【问题标题】:How to deallocate Azure Virtual Machine without waiting in C#如何在不等待 C# 的情况下释放 Azure 虚拟机
【发布时间】:2020-05-12 05:54:32
【问题描述】:

我正在使用适用于 Microsoft Azure 的 C# SDK 来停止(解除分配)虚拟机。我正在尝试使用Microsoft.Azure.Management.Compute.Fluent.IVirtualMachine.DeallocateMicrosoft.Azure.Management.Compute.IVirtualMachine.DeallocateWithHttpMessagesAsync。两者似乎都在等待虚拟机完成释放过程。

我想释放虚拟机而不阻塞等待释放完成。

我在 Azure CLI 文档中注意到有一个 --no-wait 选项。

来源:https://docs.microsoft.com/en-us/cli/azure/vm?view=azure-cli-latest#az_vm_deallocate

如何使用适用于 Azure 的 C# SDK 实现此目的?

【问题讨论】:

  • 如果我没记错的话,我认为--no-wait选项意味着命令应该在发送请求后立即终止,而不是等待操作完成。
  • 与@GauravMantri 的想法相同。我认为使用异步解除分配方法,您无需等待,因为异步说明了一切。 cancellationToken 属性与 --no-wait 具有相同的功能
  • @GauravMantri 是的,我知道。这就是我希望 C# SDK 的行为。
  • @ThuanNg 即使是异步版本也会等待。它以允许我继续的任务作为响应,但是,任务本身仍在等待虚拟机完成。这会留下一个等待 VM 完成的线程/任务。我什至不想要那个。
  • 明白。也许通过设计它会阻止您对正在使用的虚拟机执行进一步的功能(以防它仍在被释放)。也只是从微软文档中读到DeallocateWithHttpMessagesAsync 用于规模集,而不是特定的虚拟机。使用 VM Scale Set,当然是一组需要等待的 VM。

标签: c# azure azure-virtual-machine


【解决方案1】:

我找到了答案。

我可以使用Microsoft.Azure.Management.Compute.IVirtualMachine.BeginDeallocateWithHttpMessagesAsync 来启动释放过程。该方法立即返回,无需等待 VM 实际完成释放过程。

【讨论】:

    【解决方案2】:

    不知道如何使用已接受的答案,所以想分享一下 sn-p。

    using Microsoft.Azure.Management.Compute.Fluent;
    using Microsoft.Azure.Management.ResourceManager.Fluent;
    using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
    
    
    ....
    
    
    async Task DeallocateAzureVirtualMachine()
    {
        // there are other ways to obtain credentials as well. 
        // this one is related to an App registration
        var credentials = SdkContext.AzureCredentialsFactory
                        .FromServicePrincipal("clientId", "secretKey", "tenantId",
                        AzureEnvironment.AzureGlobalCloud);
    
        var restClient = RestClient
                            .Configure()
                            .WithEnvironment(AzureEnvironment.AzureGlobalCloud)
                            .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                            .WithCredentials(credentials)
                            .Build();
    
        using (var computeManagementClient = new ComputeManagementClient(restClient))
        {
            await computeManagementClient.VirtualMachines
                .BeginDeallocateWithHttpMessagesAsync("resource-group-name", "vm-name");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-10
      • 2019-02-01
      • 1970-01-01
      • 2016-07-23
      • 1970-01-01
      相关资源
      最近更新 更多