Xamarin iOS Run Task同步返回值

时间:2017-02-20 11:03:01

标签: c# ios asynchronous xamarin xamarin.ios

我有一个非异步方法应该调用显示UIAlertView的异步方法。如果单击了Button,则此异步方法返回int。

    public Task<int> ShowAlertAsync(string title, string message, params string[] buttons)
    {
        var tcs = new TaskCompletionSource<int>();

        var alert = new UIAlertView
        {
            Title = title,
            Message = message
        };

        if (buttons.Length > 0)
        {
            foreach (var button in buttons)
            {
                alert.AddButton(button);
            }
        }
        else
        {
            alert.AddButton("OK");
        }

        alert.Clicked += (s, e) => { tcs.TrySetResult((int)e.ButtonIndex); };
        alert.Show();

        return tcs.Task;
    }

如果我从异步方法调用它,这可以正常工作,但问题是我有一个肯定无法转换为异步的同步方法,所以我需要以同步方式调用此方法并等待为了回应。在sync方法获得结果后,它应该继续执行。

我尝试了许多解决方案,这些解决方案都没有编译或阻止MainThread,并且UIAlertView将不会显示。

也许有人知道我该怎么做,或者可能有更好的解决方案。

提前致谢!

1 个答案:

答案 0 :(得分:1)

可能的解决办法可能是使用ContinueWith。

例如:

public class History extends Fragment {
final int PAGE_COUNT = 3;
private String tabTitles[] = new String[]{"Tab1", "Tab2", "Tab3"};
public static final String ARG_PAGE = "ARG_PAGE";

private static final int NUM_PAGES = 3;

String medicinename,medicinepercentage,numberdosages,time;
String date,day,daypercentage;
String month,monthdata;

/**
 * The pager widget, which handles animation and allows swiping horizontally to access previous
 * and next wizard steps.
 */
private ViewPager mPager;


/**
 * The pager adapter, which provides the pages to the view pager widget.
 */
private PagerAdapter mPagerAdapter;


private int selectedPage; // set selected page

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";


DonutProgress dp;
DonutProgress dp2;
DonutProgress dp3;

public static History newInstance(int page) {
    Bundle args = new Bundle();
    args.putInt(ARG_PAGE, page);
    History fragment = new History();
    fragment.setArguments(args);
    return fragment;
}


// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private Paint progressPaint = new Paint();
private int lineHeight = 30;
private Paint incompletePaint = new Paint();

public History() {
    // Required empty public constructor
}

/**
 * Use this factory method to create a new instance of
 * this fragment using the provided parameters.
 *
 * @param param1 Parameter 1.
 * @param param2 Parameter 2.
 * @return A new instance of fragment History.
 */
// TODO: Rename and change types and number of parameters
public static History newInstance(String param1, String param2) {
    History fragment = new History();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_history, container, false);

    dp = (DonutProgress) v.findViewById(R.id.donut_progress1);
    dp2 = (DonutProgress) v.findViewById(R.id.donut_progress2);
    dp3 = (DonutProgress) v.findViewById(R.id.donut_progress3);




    if (getArguments() != null)
    {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);

    }

    mPager = (ViewPager) v.findViewById(R.id.pager); //the UI pager
    mPagerAdapter = new ScreenSlidePagerAdapter(getFragmentManager());
    mPager.setAdapter(mPagerAdapter);
    // mPager.setPageTransformer(true, new RotateDownTransformer()); //set the animation

    selectedPage = 0; //current page
    if (savedInstanceState != null) { //if app was paused, you can reopen the same page
        selectedPage = savedInstanceState.getInt("SELECTED_PAGE");
    }
    selectedPage = 1; //current page
    if (savedInstanceState != null) { //if app was paused, you can reopen the same page
        selectedPage = savedInstanceState.getInt("SELECTED_PAGE");
    }
    selectedPage = 2; //current page
    if (savedInstanceState != null) { //if app was paused, you can reopen the same page
        selectedPage = savedInstanceState.getInt("SELECTED_PAGE");
    }

    selectedPage = 3; //current page
    if (savedInstanceState != null) { //if app was paused, you can reopen the same page
        selectedPage = savedInstanceState.getInt("SELECTED_PAGE");
    }


    mPager.setCurrentItem(selectedPage);//set the current page
    mPager.setOffscreenPageLimit(4);




    return v;


    // return inflater.inflate(R.layout.fragment_history, container, false);

}


private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter{
    public ScreenSlidePagerAdapter(FragmentManager fm) {
        super(fm);
    }
    int i = 0;


    @Override
    public Fragment getItem(int position)
    {

        if(position==0){
                Log.e("Fragment","Fragment 1::"+String.valueOf(i));
                    new Progress(100).execute();
                    new Progress2(20).execute();
                    new Progress3(30).execute();

                return SlideFragment.newInstance(0, " ");}

           if(position==1){
                Log.e("Fragment","Fragment 2");

                    new Progress(40).execute();
                    new Progress2(50).execute();
                    new Progress3(90).execute();

                return Slidetwo.newInstance(String.valueOf(0), " ");}
          if (position==2)
                Log.e("Fragment","Fragment 3");

                    new Progress(50).execute();
                    new Progress2(10).execute();
                    new Progress3(40).execute();

                return SlideThree.newInstance(String.valueOf(0), " ");


    }
    @Override
    public int getCount()
    {
        return NUM_PAGES;
    }


}


class Progress extends AsyncTask<Void, Integer, Integer>
    {
        int dummyVariable = 0;
        Progress(int dummyVariable)
        {
           this.dummyVariable = dummyVariable;
        }
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dp.setMax(100);

        }

        @Override
        protected Integer doInBackground(Void... params)
        {
            for (int i = 0; i <= dummyVariable; i++)
            {
                publishProgress(i);
                try
                {
                    Thread.sleep(20);
                }
                catch (InterruptedException ie)
                {
                    ie.printStackTrace();
                }
            }
            return null;

        }

        @Override
        protected void onProgressUpdate(Integer... values)
        {
            super.onProgressUpdate(values);
            dp.setProgress(values[0]);
        }

        @Override
        protected void onPostExecute(Integer integer)
        {
            super.onPostExecute(integer);
        }
    }

    class Progress2 extends AsyncTask<Void, Integer, Integer>
    {
        int dummyVariable = 0;
        Progress2(int dummyVariable)
        {
            this.dummyVariable = dummyVariable;
        }


        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            dp2.setMax(100);
        }

        @Override
        protected Integer doInBackground(Void... params)
        {
            for (int i = 0; i <= dummyVariable; i++)
            {
                publishProgress(i);
                try {
                    Thread.sleep(20);
                }
                catch (InterruptedException ie)
                {
                    ie.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);

            dp2.setProgress(values[0]);
        }

        @Override
        protected void onPostExecute(Integer integer) {
            super.onPostExecute(integer);
        }
    }


class Progress3 extends AsyncTask<Void, Integer, Integer>
{

    int dummyVariable = 0;
    Progress3(int dummyVariable)
    {
        this.dummyVariable = dummyVariable;
    }

    @Override
    protected void onPreExecute()
    {
        super.onPreExecute();
        dp3.setMax(100);
    }

    @Override
    protected Integer doInBackground(Void... params)
    {
        for (int i = 0; i <= dummyVariable; i++) {
            publishProgress(i);
            try
            {
                Thread.sleep(20);
            }
            catch (InterruptedException ie)
            {
                ie.printStackTrace();
            }
        }
        return null;


    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        dp3.setProgress(values[0]);
    }

    @Override
    protected void onPostExecute(Integer integer) {
        super.onPostExecute(integer);
    }
}

如果需要使用当前上下文,则可以扩展ContinueWith方法

ShowAlertAsyc("title","message",...).ContinueWith(t=>
{
    //t.Result contains the return value
});