S
stassaf
Hi,
I'm trying to download several files at the same time in order to
increase
performance.
I've tried to define a method that downloads a file, delegate this
method and
call BeginInvoke in a loop.
The problem is that every BeginInvoke returns an IAsyncResult and I
don't know
how to figure out when all the calls for this methods where completed.
My Code:
public class AsyncDemo
{
// The method to be executed asynchronously.
public bool TestMethod(string fileAdd, string fileName, out int
threadId)
{
threadId = AppDomain.GetCurrentThreadId();
try
{
WebClient Client = new WebClient ();
Client.DownloadFile(fileAdd, fileName);
}
catch(Exception ex)
{
return false;
}
return true;
}
}
public delegate bool AsyncDelegate(string fileAdd, string fileName, out
int threadId);
static void Main(string[] args)
{
//files to download
string[] fileUrlArr = new string[2];
string[] fileNameArr = new string[2];
fileUrlArr[0] = "http://www.site1.com/xxx.xml";
fileNameArr[0] = "file1.xml";
fileUrlArr[1] = "http://www.site2.com/xxx.xml";
fileNameArr[1] = "file2.xml";
int threadId;
// Create an instance of the test class.
AsyncDemo ad = new AsyncDemo();
// Create the delegate.
AsyncDelegate dlgt = new AsyncDelegate(ad.TestMethod);
IAsyncResult ar=null;
for(int i=0; i<2; i++)
{
// Initiate the asychronous call.
ar = dlgt.BeginInvoke(fileUrlArr, fileNameArr,out threadId,
null, null);
}
ar.AsyncWaitHandle.WaitOne();
}
Any help will be appreciated.
Best Regards,
Assaf
I'm trying to download several files at the same time in order to
increase
performance.
I've tried to define a method that downloads a file, delegate this
method and
call BeginInvoke in a loop.
The problem is that every BeginInvoke returns an IAsyncResult and I
don't know
how to figure out when all the calls for this methods where completed.
My Code:
public class AsyncDemo
{
// The method to be executed asynchronously.
public bool TestMethod(string fileAdd, string fileName, out int
threadId)
{
threadId = AppDomain.GetCurrentThreadId();
try
{
WebClient Client = new WebClient ();
Client.DownloadFile(fileAdd, fileName);
}
catch(Exception ex)
{
return false;
}
return true;
}
}
public delegate bool AsyncDelegate(string fileAdd, string fileName, out
int threadId);
static void Main(string[] args)
{
//files to download
string[] fileUrlArr = new string[2];
string[] fileNameArr = new string[2];
fileUrlArr[0] = "http://www.site1.com/xxx.xml";
fileNameArr[0] = "file1.xml";
fileUrlArr[1] = "http://www.site2.com/xxx.xml";
fileNameArr[1] = "file2.xml";
int threadId;
// Create an instance of the test class.
AsyncDemo ad = new AsyncDemo();
// Create the delegate.
AsyncDelegate dlgt = new AsyncDelegate(ad.TestMethod);
IAsyncResult ar=null;
for(int i=0; i<2; i++)
{
// Initiate the asychronous call.
ar = dlgt.BeginInvoke(fileUrlArr, fileNameArr,out threadId,
null, null);
}
ar.AsyncWaitHandle.WaitOne();
}
Any help will be appreciated.
Best Regards,
Assaf