【问题标题】:using await inside setters [duplicate]在设置器中使用 await [重复]
【发布时间】:2016-12-16 16:23:52
【问题描述】:

我正在尝试从互联网上异步下载一些图片。我已经构建了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'.

如何使用“异步”修饰符标记设置器?

【问题讨论】:

    标签: c# xamarin


    【解决方案1】:

    简单的答案:你不能。所有属性(getset)和同步的。将其保留为 async 函数,您就很好了。

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

    请注意,仅当您没有任何其他选项时,才应使用最后一个选项。调试可能很困难,并且您可能会遇到您不希望发生的竞争条件。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2013-12-30
        • 1970-01-01
        • 2015-09-29
        • 2016-11-07
        • 2018-01-12
        • 1970-01-01
        • 2021-09-26
        • 2015-03-15
        • 2012-11-23
        相关资源
        最近更新 更多