【问题标题】:Cannot await 'Void' even when using Task即使使用任务也无法等待“无效”
【发布时间】:2015-05-22 06:18:59
【问题描述】:

我有问题。我正在尝试修改我前一段时间制作的应用程序,它仍然可以在 WP Phone 上运行,但现在我尝试运行它得到以下错误:

等待我得到:

不能等待'void'。

当我将 void 更改为任务时,错误仍然是

不能等待'void'

我什至没有void 了。

有人可以帮我吗?

namespace StreamUploadDownload
{
    using System.Threading;
    public partial class Page1 : PhoneApplicationPage
    {
        private PhotoCamera _cam;
        private double _canvasWidth;
        private double _canvasHeight;
        private MediaLibrary _library = new MediaLibrary();
        public int count = 100;
        private static readonly string[] scopes = new string[] { "wl.signin", "wl.basic", "wl.offline_access", "wl.skydrive_update", "wl.skydrive" };
        string comboValue;
        private LiveConnectClient liveClient;
        public int x = 0;
        public int y = 0;  

        public string FileText { get; set; }
        public int ComboNumber { get; set; }
        public int ConnectionOK { get; set; }

        public Page1()
        {
            InitializeComponent();    
        }

        private void OnSessionChanged(object sender, LiveConnectSessionChangedEventArgs e)
        {
            this.liveClient = (e.Status == LiveConnectSessionStatus.Connected) ? new LiveConnectClient(e.Session) : null;
            if (e.Status == LiveConnectSessionStatus.Connected)
            {
                btnSignin.Visibility = Visibility.Collapsed;
                Pildista.Visibility = Visibility.Visible;
                //Pildista2K.Visibility = Visibility.Visible;
                Pildista.Content = "Pildista";    
            }
            else
            {
                Pildista.Visibility = Visibility.Collapsed;
                //Pildista2K.Visibility = Visibility.Collapsed;
                btnSignin.Visibility = Visibility.Visible;
            }
        }    

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if ((PhotoCamera.IsCameraTypeSupported(CameraType.Primary) == true) ||
                 (PhotoCamera.IsCameraTypeSupported(CameraType.FrontFacing) == true))
            {
                if (PhotoCamera.IsCameraTypeSupported(CameraType.Primary))
                {
                    _cam = new Microsoft.Devices.PhotoCamera(CameraType.Primary);
                    _cam.Initialized += new EventHandler<CameraOperationCompletedEventArgs>(cam_Initialized);
                    _cam.CaptureImageAvailable += new EventHandler<ContentReadyEventArgs>(cam_CaptureImageAvailable);
                    viewfinderBrush.SetSource(_cam);

                    //CameraButtons.ShutterKeyPressed += OnButtonFullPress;

                    base.OnNavigatedTo(e);
                    if (PhoneApplicationService.Current.State.ContainsKey("Text"))
                    {
                        txtvalue.Text = (string)PhoneApplicationService.Current.State["Text"];
                        FileText = txtvalue.Text;
                    }
                    if (PhoneApplicationService.Current.State.ContainsKey("index"))
                    {
                        ComboNumber = (int)PhoneApplicationService.Current.State["index"];
                    }
                    else
                    {
                        // The camera is not supported on the device.
                        this.Dispatcher.BeginInvoke(delegate()
                        {
                            // Write message.    
                        });

                        // Disable UI.    
                        AFButton.IsEnabled = false;    
                    }    
                }
            }
        }

        private double GetCameraAspectRatio()
        {
            IEnumerable<Size> resList = _cam.AvailableResolutions;

            if (resList.Count<Size>() > 0)
            {
                Size res = resList.ElementAt<Size>(0);
                return res.Width / res.Height;
            }

            return 1;
        }

        void cam_Initialized(object sender, Microsoft.Devices.CameraOperationCompletedEventArgs e)
        {
            if (e.Succeeded)
            {
                this.Dispatcher.BeginInvoke(delegate()
                {
                    _canvasHeight = Application.Current.Host.Content.ActualWidth;
                    _canvasWidth = _canvasHeight * GetCameraAspectRatio();

                    viewfinderCanvas.Width = _canvasWidth;
                    viewfinderCanvas.Height = _canvasHeight;
                });
            }
        }   

        //Failinime andmine ning salvestamine.
        private async void cam_CaptureImageAvailable(object sender, Microsoft.Devices.ContentReadyEventArgs e)
        {
            if (ComboNumber == 1)
            {
                comboValue = "O";
            }
            if (ComboNumber == 2)
            {
                comboValue = "T";
            }
            if (ComboNumber == 3)
            {
                comboValue = "S";
            }
            if (ComboNumber == 4)
            {
                comboValue = "P";
            }
            if (ComboNumber == 5)
            {
                comboValue = "A";
            }
            if (ComboNumber == 6)
            {
                comboValue = "M";
            }

            string fileName = String.Format(FileText + "_" + comboValue + "_" + DateTime.Now.ToString("dd-MM-yyyy_HH-mm-ss") + ".jpg");    

            try
            {    
                LiveOperationResult operationResult = await this.liveClient.UploadAsync("/me/skydrive", fileName, e.ImageStream, OverwriteOption.Overwrite); //Cannot await 'void'    
            }

            catch (LiveConnectException ex)
            {
                // e.ImageStream.Close();
                // this.infoTextBlock.Text = "Error getting contact info: ";
                // this.infoTextBlock.Visibility = Visibility.Visible;    
            }
            finally
            {    
                e.ImageStream.Close();
                y++;
                Dispatcher.BeginInvoke(delegate()
                {
                    string b = Convert.ToString(y);
                    loobvalue2.Text = b;
                });    
            }    
        }    

        //kaameranupu vajutus.

        private void takephoto_Click(object sender, RoutedEventArgs e)
        {    
            if (_cam != null)
            {    
                _cam.CaptureImage();
                x++;
                string s = x.ToString();
                loobvalue.Text = s;    
            }    
        }   

        // Ühenduse Loomine. Session load.
        private async void connectButton_Click(object sender, RoutedEventArgs e)
        {
            bool connected = false;
            try
            {
                var authClient = new LiveAuthClient("RemovedforWeb");
                LiveLoginResult result = await authClient.LoginAsync(new string[] { "wl.signin", "wl.skydrive" }); // cannot await 'void'

                if (result.Status == LiveConnectSessionStatus.Connected)
                {
                    connected = true;
                    var connectClient = new LiveConnectClient(result.Session);
                    var meResult = await connectClient.GetAsync("me");
                    dynamic meData = meResult.Result; //cannot await 'void'
                    }
                else
                {
                    //btnSignin.Visibility = Visibility.Visible;
                }    
            }
            catch (LiveAuthException ex)
            {

            }

编辑:我添加了更多代码,并对有问题的地方发表了评论

【问题讨论】:

  • 你有两个等待,一个用于authClient.LoginAsync,一个用于connectClient.GetAsync。这些应该返回Task&lt;LiveLoginResult&gt;Task&lt;T&gt;,其中T 是meResult 的类型。他们中的任何一个都返回voidTask
  • 你说的是哪一行代码?
  • 你的错误是在另一个城堡。请显示其余代码和带有堆栈跟踪的完整错误消息。
  • @MariusBancila 当他将 Task 作为这些方法之一的返回类型时,错误消息将类似于“无法将类型 void 转换为 LiveLoginResult 或 meResult 应该是什么。因此,如果错误确实出在那段代码中,那肯定是 authClient.LoginAsyncconnectClient.GetAsync 的类型为 void。
  • 代码太多。请保留Minimal, Complete, and Verifiable

标签: c# windows-phone-8 void


【解决方案1】:
public async Task Method1 ()
{

}

public async Task<int> Method2 ()
{

}

对于上面的代码,“Method1”不返回任何值,而“Method2”返回一个“int”值。

int i = await Method2(); //this is correct
await Method2(); //this is correct
int i = await Method1(); //this is NOT correct
await Method1(); //this is also correct

以下代码行

LiveOperationResult operationResult = await this.liveClient.UploadAsync("/me/skydrive", fileName, e.ImageStream, OverwriteOption.Overwrite); //Cannot await 'void'

“UploadAsync”方法不返回任何值,如果你说“Cannot await 'void'”看起来就是这样

尝试从代码行中删除“LiveOperationResult operationResult =”,然后编写 -

await this.liveClient.UploadAsync("/me/skydrive", fileName, e.ImageStream, OverwriteOption.Overwrite);

第二行代码也一样-

LiveLoginResult result = await authClient.LoginAsync(new string[] { "wl.signin", "wl.skydrive" }); // cannot await 'void'

重写为-

await authClient.LoginAsync(new string[] { "wl.signin", "wl.skydrive" }); // cannot await 'void'

【讨论】:

  • 第一种方法完美替代void
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-30
  • 1970-01-01
  • 2021-10-29
  • 1970-01-01
相关资源
最近更新 更多