如何将结果返回到Windows Phone中的UI线程?

时间:2012-02-22 15:43:04

标签: windows-phone-7

有谁知道好主意如何将结果返回给UI线程? 我编写了这段代码,但这将是编译错误,因为它无法在异步中返回“img”。

public byte[] DownloadAsync2(Uri address)
{
    byte[] img;
    byte[] buffer = new byte[4096];

    var wc = new WebClient();

    wc.OpenReadCompleted += ((sender, e) =>
    {
        using (MemoryStream memoryStream = new MemoryStream())
        {
            int count = 0;
            do
            {
                count = e.Result.Read(buffer, 0, buffer.Length);
                memoryStream.Write(buffer, 0, count);
            } while (count != 0);

            Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    if (e.Error == null) img = memoryStream.ToArray();
                });
        }
    }
    );
    wc.OpenReadAsync(address);

    return img; //error : Use of unassigned local variable 'img'
}

1 个答案:

答案 0 :(得分:2)

将您的方法更改为:

public void DownloadAsync2(Uri address, Action<byte[]> callback, Action<Exception> exception)
{
    var wc = new WebClient();

    wc.OpenReadCompleted += ((sender, e) =>
    {
        using (MemoryStream memoryStream = new MemoryStream())
        {
            int count = 0;
            do
            {
                count = e.Result.Read(buffer, 0, buffer.Length);
                memoryStream.Write(buffer, 0, count);
            } while (count != 0);

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                if (e.Error == null) callback(memoryStream.ToArray());
                else exception(e.Error);
            });
        }
    }
    );
    wc.OpenReadAsync(address);
}

用法:

DownloadAsync2(SomeUri, (img) =>
{
    // this line will be executed when image is downloaded, 
    // img - returned byte array
},
(exception) =>
{
    // handle exception here
});

或(没有lambda表达式的旧式代码):

DownloadAsync2(SomeUri, LoadCompleted, LoadFailed);

// And define two methods for handling completed and failed events

private void LoadCompleted(byte[] img)
{
    // this line will be executed when image is downloaded, 
    // img - returned byte array
}

private void LoadFailed(Exception exception)
{
    // handle exception here
}