Xamarin WCF电话

时间:2017-01-17 10:08:14

标签: xamarin.android

我试图在我的xamarin android应用程序中调用WCF服务,但是当它调用该方法突然应用程序退出whiteout任何异常。 我使用了tutorial from Xamarin we site

这是我的MainAxtivity.cs文件内容:

using Android.App;
using Android.Widget;
using Android.OS;
using System.Net;
using System.ServiceModel;
using System;

namespace TaskTracking.Droid
{
    [Activity(Label = "TaskTracking.Droid", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        Button button1 = null;
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.Main);
            button1 = FindViewById<ButtonResource.Id.button1);
            button1.Click += Button1_Click;
        }

        private void Button1_Click(object sender, System.EventArgs e)
        {
            try
            {
                EndpointAddress EndPoint = new EndpointAddress("http://10.10.2.162/TaskTracking.Service/TaskService.svc");
                BasicHttpBinding binding = new BasicHttpBinding
                {
                    Name = "basicHttpBinding",
                    MaxBufferSize = 2147483647,
                    MaxReceivedMessageSize = 2147483647
                };
                System.TimeSpan timeout = new System.TimeSpan(0, 0, 30);
                binding.SendTimeout = timeout;
                binding.OpenTimeout = timeout;
                binding.ReceiveTimeout = timeout;

                var client = new TaskServiceClient(binding, EndPoint);
                client.GetDataAsync(2);  /// Problem is here
                client.GetDataCompleted += Client_GetDataCompleted;
            }
            catch (Exception ex) // Never catch anything
            {
                var message = ex.ToString();
            }
        }

        private void Client_GetDataCompleted(object sender, GetDataCompletedEventArgs e)
        {
            var res = e.Result;
            Toast.MakeText(this, res, ToastLength.Long);
        }
    }
}

1 个答案:

答案 0 :(得分:1)

假设您已经正确设置了WCF,请尝试在client.GetDataCompleted来电之前订阅client.GetDataAsync(2);事件。

var client = new TaskServiceClient(binding, EndPoint);
client.GetDataCompleted += Client_GetDataCompleted;
client.GetDataAsync(2);

此外,您尝试在后台线程而不是Toast中创建UIThread。因此,请按以下方式更改Client_GetDataCompleted代码:

private void Client_GetDataCompleted(object sender, GetDataCompletedEventArgs e)
{
    var res = e.Result;
    RunOnUiThread(() => Toast.MakeText(Application.Context, res, ToastLength.Long).Show());
}

有关UIThread here

的更多信息