asychronicly downloading files

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
 
N

Nicholas Paldino [.NET/C# MVP]

Assaf,

After each call to BeginInvoke, place the WaitHandle returned by the
IAsyncResult implementation into an array of WaitHandles.

When you are done looping, and know how many wait handles you need to
wait on, pass the array to the static WaitAll method on the WaitHandle
class.

Hope this helps.
 
S

stassaf

10x a lot Nicholas.
I'll give it a try, but it looks like the right way to do it.

Again 10x,
Assaf.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top