【问题标题】:C# - Xamarin - HttpClient - Operation is not valid due to the current state of the object - iOSC# - Xamarin - HttpClient - 由于对象的当前状态,操作无效 - iOS
【发布时间】:2016-10-25 16:01:54
【问题描述】:

我正在开发一个发出 HTTP 请求的跨平台库。它在 Android 上运行良好,但是当我尝试在 iOS 上使用它时出现异常,我不知道如何修复它。

这是我的代码:

// method from cross platform library

Task.Factory.StartNew(delegate
{
    try
    {
        var client = new HttpClient();
        // some other setup stuff
        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.post, "http://myurl.com...");

        var task = client.SendAsync(request);
        task.Wait(); // Exception thrown on this line

        var response = task.Result;

        var responseString = response.Content.ReadAsStringAsync().Result;
    }
    catch (Exception e)
    {
    }
}

task.Wait(); 上,我得到一个System.AggregateException,内部异常为System.InvalidOperationException,上面写着Operation is invalid due to the current state of the object.

试图找到一些解决方案,我发现问题可能是通过在 UI 线程上调用它引起的。但这就是将这一切都包含在 Task.Factory.StartNew 中的全部意义。

我已经尝试了所有我知道的方法,但仍未解决问题。任何帮助将不胜感激。

编辑:

我决定在 iPhone 模拟器上尝试我的解决方案。这是一个运行 iOS 10 的 iPhone 6 模拟器。我的物理设备是一样的。它可以在模拟器上运行,但由于某种原因不能在物理设备上运行……很奇怪。

编辑 2:

感谢@YuriS 找到解决方案。

发件人:https://forums.xamarin.com/discussion/36713/issue-with-microsoft-http-net-library-operation-is-not-valid-due-to-the-current-state-of-the-objec

你可以做的是: 1)转到ios项目的参考资料 2) 编辑参考文献 3)检查'System.Net.Http'

android 的行为是一样的。

【问题讨论】:

  • 你不能保证启动一个新任务它实际上是在一个单独的线程池线程上执行的,可以吗?你为什么还要这样做?
  • @Cheesebaron 我怎么能保证这是在一个单独的线程池线程上呢?
  • @JaredPrice 我对您为什么要这样做也感到困惑,但是您在“跨平台库”中使用的 Android 和 iOS 项目上是否安装了相同的 Nuget 包?
  • @SushiHangover 是的。你有什么困惑?有没有更好的方法来做到这一点?
  • 肯定有更好的方法来做到这一点。如果您愿意(让我知道),我可以提供答案,但我无法重现您所描述的内容。我复制了你的代码,它可以在我的手机和模拟器上运行。我在按下按钮时调用此功能。你什么时候调用它?

标签: ios xamarin httpclient invalidoperationexception aggregateexception


【解决方案1】:

这里描述的问题可能很少: https://forums.xamarin.com/discussion/36713/issue-with-microsoft-http-net-library-operation-is-not-valid-due-to-the-current-state-of-the-objec

https://bugzilla.xamarin.com/show_bug.cgi?id=17936

"Operation is not valid" error at Xamarin.iOS project with HttpClient

http://motzcod.es/post/78863496592/portable-class-libraries-httpclient-so-happy

似乎所有帖子都指向 System.Net.Http

不管有什么问题,都有更好的方法来做到这一点。其中之一:

public static async Task PostRequest()
{
    try
    {
        HttpClient client = new HttpClient();
        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "https://myuri");
        //request.Headers.Add("", "");
        var response = await client.SendAsync(request);
        var responseString = await response.Content.ReadAsStringAsync();
    }
    catch (Exception ex)
    {

    }
}

如果你想等到函数完成你调用

await PostRequest();

如果您不需要等待,则只需在调用中省略“等待”或使用

PostRequest.ContinueWith((t)=>
{
});

您还需要在函数中处理异常,因此可能只返回 Task 并不是最好的。我只是根据原始函数签名来回答

【讨论】:

    猜你喜欢
    • 2010-10-18
    • 2012-07-14
    • 1970-01-01
    • 2020-04-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多