i have a question about OpenReadAsync using anonymous method.
It seems like that when i use the anonymous method for OpenReadAsync it doesn't run in a separate thread.
I try to read an image from an url and insert it in a excel. (not important)
If i run this code i get every output from Debug.WriteLine (in wrong order though)
Output is:
- Starting OpenReadAsync
- Next line WaitAll() method
- WaitAll passed
- Begin of OpenReadCompleted
- Next line .Set() method
- End of OpenReadCompleted
My goal would be:
- Starting OpenReadAsync
- Next line WaitAll() method
- Begin of OpenReadCompleted
- Next line .Set() method
- End of OpenReadCompleted
- WaitAll passed
The question now is, why does the OpenReadAsync Method never get called when i set a breakpoint on the line
Debug.WriteLine("-> Next line WaitAll() method");
The OpenReadAsync method call is passed at this point but no sign from the other thread.
Output with breakpoint set is only:
Hope i was able to clarify my question/problem and apologise for my english.
Any help highly appreciated.
This is the code:
// open file dailog for selecting export file
sDialog.Filter = "Excel Files(*.xls)|*.xls";
if (sDialog.ShowDialog() == true)
{
// create a workbook object
Workbook workbook = new Workbook();
//Create a worksheet object
Worksheet worksheet1 = new Worksheet("Org-Export");
// create a spreadsheet picture object
Lite.ExcelLibrary.SpreadSheet.Picture pic = new Lite.ExcelLibrary.SpreadSheet.Picture();
foreach (var item in grdOrg.Items)
{
Organization organization = item as Organization;
WaitHandle[] waitHandles = new WaitHandle[] { new AutoResetEvent(false) };
WebClient webClient = new WebClient();
Debug.WriteLine("-> Starting OpenReadAsync");
webClient.OpenReadAsync(new Uri(organization.Picture, UriKind.RelativeOrAbsolute));
webClient.OpenReadCompleted += (s, args) =>
{
Debug.WriteLine("-> Begin of OpenReadCompleted");
try
{
Stream stream = args.Result;
int length = (int)stream.Length;
byte[] buffer = new byte[length];
int count;
int sum = 0;
while ((count = stream.Read(buffer, sum, length - sum)) > 0)
sum += count;
//ImageTranslator.TranslateImageToBytes translate an image control to byte array
// that will be used by excel picture object to plot picture in excel file.
pic.Image = new Lite.ExcelLibrary.SpreadSheet.Image(buffer, 0xF01E);
//set picture size
pic.TopLeftCorner = new CellAnchor(1, 1, 10, 10);
pic.BottomRightCorner = new CellAnchor(8, 5, 10, 10);
// add picture to spreadsheet
worksheet1.AddPicture(pic);
Debug.WriteLine("-> Next line .Set() method");
((AutoResetEvent)waitHandles[0]).Set();
Debug.WriteLine("-> End of OpenReadCompleted");
}
catch (Exception ex)
{ }
};
Debug.WriteLine("-> Next line WaitAll() method");
//WaitHandle.WaitAll(waitHandles);
Debug.WriteLine("-> WaitAll passed");
}
/// add worksheet to workbook
workbook.Worksheets.Add(worksheet1);
// get the stream of selected file
Stream sFile = sDialog.OpenFile();
// save excel file
workbook.Save(sFile);
}