我对使用匿名方法的OpenReadAsync有疑问。
似乎当我使用OpenReadAsync的匿名方法时,它不会在单独的线程中运行。
我尝试从网址中读取图片并将其插入Excel中。 (不重要)
如果我运行此代码,我将获得Debug.WriteLine的每个输出(但顺序错误)
输出是:
我的目标是:
现在的问题是,为什么在线路上设置断点时永远不会调用OpenReadAsync方法
Debug.WriteLine("-> Next line WaitAll() method");
此时传递OpenReadAsync方法调用但没有来自另一个线程的符号。
设置断点的输出仅为:
希望我能够澄清我的问题/问题并为我的英语道歉。
任何帮助高度赞赏。
这是代码:
// 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);
}
答案 0 :(得分:0)
我自己找到了原因。
问题在于我阻止了主线程,因此每个线程都停止在WaitHandle.WaitAll(waitHandles);
行上工作(如果设置了断点,则相同)
解决方案:
使用后台工作程序来运行代码(来自主线程的代码),一切正常。
编辑:看这个 - > http://blogs.planetsoftware.com.au/paul/archive/2010/12/05/waiting-for-a-task-donrsquot-block-the-main-ui-thread.aspx