在Facebook照片上传期间捕获由网络错误引起的异常

时间:2012-11-08 03:22:44

标签: c# wpf multithreading error-handling facebook-c#-sdk

我已将照片上传到Facebook活动页面,主要是按照tutorial进行操作。到目前为止,结果令人满意,大部分时间都将照片上传到活动页面。但是,有时当程序上传照片,并且网络连接滞后或被切断时,程序会崩溃并抛出System.AggregateException,并显示以下消息:

A Task's exception(s) were not observed either by Waiting on the Task or accessing its Exception property. As a result, the unobserved exception was rethrown by the finalizer thread.

通过初步检查,InnerException是:

[Facebook.WebExceptionWrapper]: {"The underlying connection was closed: An unexpected error occurred on a receive."}

,上面异常的InnerException是System.IO.IOException,IOException中有另一个System.Net.Socket.SocketException,其中两个错误消息都描述了类似{"An established connection was aborted by the software in your host machine"}的内容。

例外的StackTrace只给我:

at System.Threading.Tasks.TaskExceptionHolder.Finalize()

现在很明显,这个问题是由系统有时会遇到的网络连接蹩脚引起的。那么,我如何或在哪里根据此tutorial引用的代码处理此异常?我不知道在另一个线程中发生这种情况时我应该把try-catch块放在哪里,或者对我来说似乎是这样。

先谢谢!

来自tutorial的参考代码:

var mediaObject = new FacebookMediaObject
                              {
                                  ContentType = "image/jpeg",
                                  FileName = Path.GetFileName(_filename)
                              }
                              .SetValue(File.ReadAllBytes(_filename));

var fb = new FacebookClient(_accessToken);
fb.PostCompleted += fb_PostCompleted;
fb.PostAsync("/me/photos", new Dictionary<string, object> { { "source", mediaObject } });

public void fb_PostCompleted(object sender, FacebookApiEventArgs e)
{
  if (e.Cancelled)
  {
    var cancellationError = e.Error;
    MessageBox.Show("Upload cancelled");
  }
  else if (e.Error == null)
  {
    // upload successful.
    MessageBox.Show(e.GetResultData().ToString());
  }
  else
  {
    // upload failed
    MessageBox.Show(e.Error.Message);
  }
}

0 个答案:

没有答案