Я хочу получить строку из переменной "inputtext" в ShowKeyboard(...), но не знаю, как это сделать. Я всегда получаю сообщение об ошибке в этой строке кода:
KeyboardTextUsername = NewGetKeyboard(Tokenusername, "Registration", "Username", "Choose a username", false);
Error CS0029: Cannot implicitly convert type 'System.Threading.Tasks.Task' to 'string'
Обновлено: после изменения кода я получаю это сообщение об ошибке:
KeyboardTextUsername = await NewGetKeyboard(Tokenusername, "Registration", "Username", "Choose a username", false);
Error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
Что я делаю неправильно? Я не знаю, как решить эту проблему.
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
TouchPanel.EnabledGestures = GestureType.Tap;
UsernameRectangle = new Microsoft.Xna.Framework.Rectangle(400, 230, 150, 100);
CursorRectangle = new Microsoft.Xna.Framework.Rectangle(-150, -100, 10, 10);
}
protected override void Update(GameTime gameTime)
{
while (TouchPanel.IsGestureAvailable)
{
GestureSample gs = TouchPanel.ReadGesture();
switch (gs.GestureType)
{
case GestureType.Tap:
CursorRectangle = new Microsoft.Xna.Framework.Rectangle((int)gs.Position.X, (int)gs.Position.Y, 10, 10);
CheckButtonPressed = true;
break;
}
}
if ((UsernameRectangle.Intersects(CursorRectangle)) && (CheckButtonPressed == true))
{
KeyboardTextUsername = await NewGetKeyboard(Tokenusername, "Registration", "Username", "Choose a username", false);
}
CheckButtonPressed = false;
base.Update(gameTime);
}
public async Task<string> NewGetKeyboard(string Token, string MessageBoxTitle, string MessageBoxDescription, string Text, bool IsPassword)
{
string keyboardtext = "";
string savedtext = await Getlogin(Token);
if (savedtext == "")
savedtext = Text;
keyboardtext = await ShowKeyboard(Token, MessageBoxTitle, MessageBoxDescription, savedtext, IsPassword);
return keyboardtext;
}
public async Task<string> Getlogin(string token)
{
string Text = "";
try
{
Text = await SecureStorage.GetAsync(token);
}
catch (Exception ex)
{
// Possible that device doesn't support secure storage on device.
Console.WriteLine("secure storage not supported on this device");
}
return Text;
}
private async Task<string> ShowKeyboard(string token, string messageboxtitle, string messageboxdescription, string text, bool ispassword)
{
string inputtext = "";
await Task.Run(async () =>
{
var result = await KeyboardInput.Show(messageboxtitle, messageboxdescription, text, ispassword);
if (null != result)
{
inputtext = result;
}
});
try
{
await SecureStorage.SetAsync(token, inputtext);
}
catch (Exception ex)
{
// Possible that device doesn't support secure storage on device.
Console.WriteLine("secure storage not supported on this device");
}
return inputtext;
}
@gunr2171 Gunr2171 Самый популярный ответ на этот обман ужасен!
Это одна из причин, по которой слово «асинхронный» обычно используется в любых методах, которые являются асинхронными, например. изменение NewGetKeyboard на NewGetKeyboardAsync, чтобы напомнить вам, что вам нужно дождаться асинхронной задачи.
Я добавил больше кода в свой вопрос.





NewGetKeyboard — это метод async, который следует вызывать с помощью ключевого слова await.
protected void async MyButtonClickHandler(object sender, EventArgs args)
{
...
KeyboardTextUsername = await NewGetKeyboard(Tokenusername, "Registration", "Username", "Choose a username", false);
...
}
Это не работает, потому что код не находится в асинхронном методе. Я использую NewGetKeyboard сразу после нажатия кнопки.
@Jerry_Champ, вы можете пометить обработчики событий (действия кнопок и т. д.) как async, это приемлемое время Только для использования метода async void, потому что вы ограничены типом возврата void с обработчиком событий.
@Jerry_Champ, не могли бы вы также вставить нужное количество кода, чтобы дать нам некоторый контекст? Вы говорите здесь, например, что используете NewGetKeyboard после нажатия кнопки, но ничего не говорите об этом в своем вопросе. Это гарантирует, что люди готовы дать правильный ответ.
Я добавил больше кода в свой вопрос.
Вы не можете просто вызывать await вне такого метода, это также относится и к вашим условиям. await должен быть внутри асинхронного метода; и условия должны быть внутри метода (будь то асинхронный или обычный (синхронный) метод). В этом случае он будет находиться в вашем асинхронном методе.
public async Task<string> CallNewGetKeyboard(UsernameRectangle userRec, bool CheckButtonPressed, string tokenUserName, string messageBoxTitle, string messageBoxDescription, string messageBoxText, bool isPassword)
{
if ((userRec.Intersects(CursorRectangle)) && (CheckButtonPressed == true))
{
var KeyboardTextUsername = await NewGetKeyboard(tokenUsername, messageBoxTitle, messageBoxDescription, messageBoxText, isPassword);
return KeyboardTextUsername;
}
}
Вот немного более короткая версия приведенного выше кода.
public async Task<string> CallNewGetKeyboard(UsernameRectangle userRec, bool CheckButtonPressed, string tokenUserName, string messageBoxTitle, string messageBoxDescription, string messageBoxText, bool isPassword)
{
//I took out ==true because it's redundant
if ((userRec.Intersects(CursorRectangle)) && (CheckButtonPressed))
{
//and return the data without assigning it
return await NewGetKeyboard(tokenUsername, messageBoxTitle, messageBoxDescription, messageBoxText, isPassword);
}
}
Если вы не хотите делать это асинхронным
KeyboardTextUsername = NewGetKeyboard(Tokenusername, "Registration", "Username", "Choose a username", false).GetAwaiter().GetResult();
Вам нужно
awaitЗадание. Пытаюсь найти дубликат.