0

I'm quite new with facebooksdk, but I have a winform project in c# to perform simple status posting & photo upload using it.

So far so good with the SDK, however, what's the difference between FacebookClient.Post & FacebookClient.PostTaskAync?

I used the following code to post photo to my facebook account:

public static void uploadPhoto(string fPath, string userMsg, string imgType = "")
{
    var fb = new FacebookClient(AccessToken);
    if (imgType.Equals(""))
        imgType = "image/jpeg";

    using (var file = new FacebookMediaStream
    {
        ContentType = imgType,
        FileName = Path.GetFileName(fPath)
    }.SetValue(File.OpenRead(fPath)))
    {
        dynamic result = fb.Post("me/photos",
            new { message = userMsg, file });
    }
}

But, when the file size is huge, the above method will "hang" my system as the main thread is still working, so I tried the following:

dynamic result = fb.PostTaskAsync("me/photos",
                  new { message = userMsg, file });

but it just doesn't work (at least the photo is not being uploaded to my fb account)...

What I want actually is to avoid the "hanging" feeling on my system, and I've even tried "Application.DoEvents()" but with NO luck.

Any suggestion to handle for this issue? Shall I use another Thread to handle this photo upload? Or?

Thanks for all the answers & comments.

cuongle
  • 74,024
  • 28
  • 151
  • 206
  • 1
    Above, 'dynamic result = fb.PostTaskAsync' should be 'dynamic result = await fb.PostTaskAsync', as the return value of PostTaskAsync is a Task, not the return object. Adding the await will asynchronously yield the return object. – Jon Rea Oct 15 '12 at 17:21
  • Dear Jon, please read my comment below regarding await / async on VS2010 SP1, .net 4.0. thanks – marcus.the.programmer Oct 16 '12 at 10:06

2 Answers2

0

Have you tried using async/await?

Obviously quite a minimal example below, but note:

  • the method is tagged with 'async'
  • the return type is Task (or Task < T > )
  • the facebook method is changed to: 'await fb.PostTaskAsync('

This means that the result is only marshaled back to the UI thread once complete, and your UI will remain responsive. Please see: http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        this.Load += OnLoad;
    }

    private const string AccessToken = "xxxxxxxxxxxxxx";
    private const string imgType = "image/jpeg";
    private const string fPath = "c:\bob.jpg";
    private const string userMsg = "My Message";

    private async void OnLoad(object sender, EventArgs e)
    {
        await DoSomething();
    }

    private async Task DoSomething()
    { 
        var fb = new FacebookClient(AccessToken);

        using (var file = new FacebookMediaStream
        {
            ContentType = imgType,
            FileName = Path.GetFileName(fPath)
        }.SetValue(File.OpenRead(fPath)))
        {
            dynamic result = await fb.PostTaskAsync("me/photos",
                new { message = userMsg, file });
        }
    }
}
Jon Rea
  • 9,337
  • 4
  • 32
  • 35
  • Note that these keywords are only available in the recently released version of .NET. If you're using an older version you'll need to use a continuation on the `Task` that the method returns explicitly. – Servy Oct 15 '12 at 17:28
  • Dear Jon, I saw the await & async method, but I can't find any library which supports await / async in VS2010 SP1 .NET 4.0. Any idea? – marcus.the.programmer Oct 16 '12 at 10:02
  • Hi Servy, I tried to use Task to handle this case, but is there anything that I need to take care for the task status? Asking so because I use the Task inside my singleton class. Do I need to create one new task at a time when calling this? Please advise. thanks. – marcus.the.programmer Oct 16 '12 at 15:11
  • Also - do have a look at this: http://stackoverflow.com/questions/9110472/using-async-await-on-net-4 – Jon Rea Oct 17 '12 at 11:57
  • You can download the VS 2010 Async CTP here: http://www.microsoft.com/en-us/download/details.aspx?id=9983 – Jon Rea Oct 17 '12 at 12:01
0

It seems that I managed to handle it using System.Threading.Tasks on my VS2010 .net4.0 with the followings:

    // For Tasks
    private static Task _taskUpload = null;
    private static string _fPath = "";
    private static string _userMsg = "";
    private static string _imgType = "";

    /// <summary>
    /// used to post photo to facebook
    /// </summary>
    /// <param name="fPath"></param>
    /// <param name="userMsg"></param>
    /// <param name="imgType"></param>
    public static void uploadPhoto(string filePath, string userMsg, string imgType = "")
    {
        // Assign Values
        _fPath = filePath;
        _userMsg = userMsg;
        _imgType = imgType;

        // Start Task
        _taskUpload = Task.Factory.StartNew(new Action(processUploadPhoto));

    }

    /// <summary>
    /// Used to process actual upload of photo to FB
    /// </summary>
    private static void processUploadPhoto()
    {
        var fb = new FacebookClient(AccessToken);
        if (_imgType.Equals(""))
            _imgType = "image/jpeg";

        using (var file = new FacebookMediaStream
        {
            ContentType = _imgType,
            FileName = Path.GetFileName(_fPath)
        }.SetValue(File.OpenRead(_fPath)))
        {
            dynamic result = fb.Post("me/photos",
                new { message = _userMsg, file });
        }
    }

Thanks for all your advices.

  • Yup - Task.Factory.StartNew will start a new asynchronous background action on the ThreadPool. Note, that if you need to update your UI from this background worker task - you will need to Dispatch the UI-control update back to the UI thread. – Jon Rea Oct 17 '12 at 11:52