2

使用此代码,用户必须等到所有图像都加载完毕。我想将这些图像异步加载到列表框中,这样用户就不必等待了。我怎么做?

    public photos()
    {
        InitializeComponent();
        refreshView();
    }

    private void refreshView()
    {
        string[] fileNames = storage.GetFileNames();
        for (int i = 0; i < fileNames.Length; i++)
        {
            image = new Image();
            FileStream jpegStream = storage.OpenFile(fileNames[i], FileMode.Open, FileAccess.Read);
            image.Source = PictureDecoder.DecodeJpeg(jpegStream, 200, 200);
            jpegStream.Dispose();
            photoList.Items.Add(image);
        }
    }
4

1 回答 1

3

你可以使用一个BackgroundWorker.

BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += (o, args) =>
    {
        //now you have a choice: get all images and add when all are retrieved,
        //or get images asynchronously here too...
        //probably best to do the latter:

        string[] fileNames = storage.GetFileNames();
        Parallell.ForEach(fileNames, file =>
        {
            Image image = new Image();
            using(FileStream jpegStream = storage.OpenFile(fileNames[i], FileMode.Open, FileAccess.Read))
            {
                image.Source = PictureDecoder.DecodeJpeg(jpegStream, 200, 200);
            }
            Dispatcher.BeginInvoke(() => photoList.Items.Add(image));
        }
    };
bw.RunWorkerAsync();
于 2013-05-22T15:10:56.883 回答