Azure表存储 - CreateTableIfNotExists悬挂 - 以前工作

时间:2016-04-26 14:15:14

标签: azure asp.net-web-api azure-storage

我一直在努力让一些代码在一台新机器上运行..我以为我终于有了它的工作但现在当我运行它时,代码挂起来试图创建表存储(或实际上得到对它的引用,因为它已经存在)...我知道必须确保它一直是异步并且这段代码正在运行......我现在已经改变了它以尝试和改进它并让它在这台机器上工作,但有些事情是不对的......所以在Repo的构造函数中我这样做....

public LdsRepo() 
    {

        if (!GetTableRef("licensedatesummary").Result)
        {
            throw new Exception("It broke!");
        }
    }

和我的GetTableReference方法(在基类上)是这样的......

protected async Task<bool>  GetTableRef(string tableRef)
    {
        try
        {
            if (string.IsNullOrEmpty(StorageAccountName) || string.IsNullOrEmpty(AuthKey))
            {
                throw new ArgumentNullException(nameof(tableRef),
                    "storageaccountname or authk are not set in the config");
            }
            if (_tableClient == null)
                _tableClient =
                    new CloudStorageAccount(new StorageCredentials(StorageAccountName, AuthKey), true)
                        .CreateCloudTableClient();
            if (_table == null)
            {
                // Create the CloudTable object that represents the referenced table.
                _table = _tableClient.GetTableReference(tableRef);
                var x =  _table.CreateIfNotExistsAsync();
                return await x;
            }
            return true;
        }
        catch (Exception ex)
        {
            Trace.WriteLine(ex.Message);
            Trace.WriteLine(ex.ToString());
            return false;
        }
    }

如果有帮助......这是我的包配置......

<packages>
<package id="Microsoft.Azure.KeyVault.Core" version="1.0.0" targetFramework="net452" />
<package id="Microsoft.Data.Edm" version="5.7.0" targetFramework="net452" />
<package id="Microsoft.Data.OData" version="5.7.0" targetFramework="net452" />
<package id="Microsoft.Data.Services.Client" version="5.7.0" targetFramework="net452" />
<package id="Microsoft.Web.WebJobs.Publish" version="1.0.11" targetFramework="net452" />
<package id="Microsoft.WindowsAzure.ConfigurationManager" version="3.2.1" targetFramework="net452" />
<package id="Newtonsoft.Json" version="8.0.3" targetFramework="net452" />
<package id="System.Spatial" version="5.7.0" targetFramework="net452" />
<package id="WindowsAzure.Storage" version="7.0.0" targetFramework="net452" /> </packages>

最后是我的实际WebApi控制器......

[EnableCors(origins: "*", headers: "*", methods: "*")]
[RoutePrefix("api")]
public class LinkDataController : ApiController
{
    private readonly IFloatingObjectRecordRepo _repo;
    public LinkDataController()
    {
        _repo = new FloatingObjectRecordRepo();
    }
    [HttpGet, Route("linkdata/{id}")]
    public async Task<IHttpActionResult> Get(string id)
    {
        try
        {
            if (string.IsNullOrEmpty(id))
            {
                return BadRequest();
            }
            var retStr = await  _repo.SearchById(id);
            if (retStr == "Not found")
                return new IsoncOkResult<KeyValuePair<string, string>>(
                    new KeyValuePair<string, string>(id, retStr), this);
            var g = Guid.NewGuid();
            var f = await _repo.Add(new FlorData
            {
                CreatedBy = "Ais Integration Search",
                Mmsi = id,
                CreatedOn = DateTime.Now,
                GeneratedId = g,
                RowKey = g.ToString()
            });
            retStr = f.GeneratedId.ToString();
            return new IsoncOkResult<KeyValuePair<string, string>>(new KeyValuePair<string, string>(id, retStr), this);
        }
        catch (Exception ex)
        {
            Trace.TraceError($"Error Searching / Creating AIS Link Data: {ex}");
            return BadRequest(ex.ToString());
        }
    }
   }

我在这里搜索得非常广泛,但每次有人都没有跟踪异步链,我想我正在做什么?

1 个答案:

答案 0 :(得分:4)

使用时

if (!GetTableRef("licensedatesummary").Result)

你错过了#34; Async的所有方式&#34;,请参阅This question了解await Task和Task.Result之间的区别。

有几个选项可以解决这个问题,这里只有两个:

  1. 您可以更改&#34; GetTableRef&#34;同步(如果这是你对这个方法的唯一用法,那么通过使用CreateIfNotExists()方法而不是CreateIfNotExistsAsync(),这应该是一个不错的选择,因为只有在阻塞上下文中使用异步方法没有好处)。 LI>
  2. 请参阅How to call async method in constructor,其中介绍了此类方案的一些技巧