Измените свой метод на:
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
});
Или (код в старом стиле без лямбда-выражений):
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
}