Showing posts with label Windows Phone. Show all posts
Showing posts with label Windows Phone. Show all posts

Monday, 3 November 2014

How to use the .Net ThreadPool

As many of you have requested, here are a few simple ways you can execute code in a thread using the .Net native ThreadPool.
It works on Windows, Unity (Mono, Android, iOS, Windows Phone)

The simplest case first: Executing a method disregarding the argument
private void SimpleThreadPoolTest()
{
  ThreadPool.QueueUserWorkItem(new WaitCallback(SimpleMethod));
}  

private void SimpleMethod(object ignoredArg)
{
  Console.WriteLine("Method called inside a thread");
}


As you may have noticed, the WaitCallback delegate takes one argument of type object, which we're ignoring right now.
But if you need to use, just pass any object as the second argument of QueueUserWorkItem, like:
private void ParameterizedThreadPoolTest()
{
  string arg = "This is a string parameter";
  ThreadPool.QueueUserWorkItem(new WaitCallback(SimpleMethod), arg);
}  

private void WaitCallback(object arg)
{
  Console.WriteLine("Executing inside a thread with argument "+arg);
}


You can also use lambda expressions instead of methods
private void LambdaThreadPoolTest()
{
  // unusedArgument is required, even though we're not using it, because WaitCallback takes 1 argument
  ThreadPool.QueueUserWorkItem(new WaitCallback(
        (unusedArgument)=>
        {
          // do something
          // then do something else
          Console.WriteLine("This is a lambda function running inside a thread");
        }
  ));
}  

Wednesday, 29 October 2014

How to download files asynchronously using only HTTP

all you need is these 2 simple methods in your class.
private void downloadFile(string fileUrl)
{ 
  HttpWebRequest request;
 
  request = WebRequest.Create(fileUrl) as HttpWebRequest;
  // this reduces connection time considerably but it's not supported in windows phone 8
  request.Proxy = null; 
 
  if(request != null)
  {
    request.BeginGetResponse(downloadFile, request); 
  }
}
 
private void downloadFile(IAsyncResult responseResult)
{   
  HttpWebRequest request = responseResult.AsyncState as HttpWebRequest ;
  if(request != null)
  {
    // the using here is VERY important if you don't want leaks
    using (WebResponse response = request.EndGetResponse(responseResult))
    {
      if(((HttpWebResponse)response).StatusCode == HttpStatusCode.OK)
      {
        // if you want to use a dynamic file location, just make the file name a member variable in your class
        using(FileStream fileStream = File.Open(@"c:\files\my_downloaded.file", FileMode.Create))
        {
          Stream source = response.GetResponseStream();
          int bytesRead;
          byte[] streamBuffer = new byte[1024*64];
          while ((bytesRead = source.Read(streamBuffer, 0, streamBuffer.Length)) > 0)
          {
            fileStream.Write(streamBuffer, 0, bytesRead);
          }
        }
      }
    }
  }
}