在setter中使用await

时间:2016-08-10 10:27:39

标签: c# xamarin

我试图从互联网上异步下载一些图片。我已经构建了GetImageBitmapFromUrl方法,如下所示

async Task<Bitmap> GetImageBitmapFromUrl(string url)
{
    Bitmap imageBitmap = null;
    try
    {
        using (var webClient = new WebClient())
        {
            var imageBytes = await webClient.DownloadStringTaskAsync(url);
            if (imageBytes != null && imageBytes.Length > 0)
            {
                imageBitmap = BitmapFactory.DecodeByteArray(Encoding.ASCII.GetBytes(imageBytes), 0, imageBytes.Length);
            }
        }
    }
    catch
    {
        //Silence is gold.
    }
    return imageBitmap;
}

我现在正试图在我的setter中调用此方法

List<string> _pictures;
Bitmap[] imageBitmap;
int currentPic = 0;
ImageView gellaryViewer;
public List<string> pictures
{
    set
    {
        if (value.Count == 0)
        {
            gellaryViewer.Visibility = ViewStates.Gone;
        }
        else
        {
            gellaryViewer.Visibility = ViewStates.Visible;
            _pictures = value;
            currentPic = 0;
            imageBitmap = new Bitmap[value.Count];
            for (int i = 0; i < value.Count; i++)
                //The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
                imageBitmap[i] = await GetImageBitmapFromUrl(value[i]);
            displayPic();
        }
    }
    get { return _pictures; }
}

但是我收到了这个错误 The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.

如何使用&#39; async&#39;标记设置器?改性剂?

2 个答案:

答案 0 :(得分:0)

查看此问题的答案:How to call an async method from a getter or setter?

话虽如此,我强烈建议将更新功能从属性移到单独的方法。属性旨在提供事物的当前状态,而不是无限期地阻塞。

答案 1 :(得分:0)

简单回答:你不能。所有属性(getset)和同步。保持async功能并且你很好。

复杂的答案:你可以,但它很难看。将async函数设为私有函数,并使用set方法调用它。但由于set是同步的,而调用方法是async,因此您必须以不同方式进行此调用。查看this SO post了解各种选项。

此注释最后一个选项仅在您没有任何其他选项时使用。调试可能很难,你可能会遇到你不想发生的竞争条件。