When you use a method that returns a Task
, you need to await
the result to access the actual object. This is because the method runs asynchronously, and the result is not immediately available. Here’s how you can modify your controller to work with the async method:
csharppublic async Task YourControllerAction()
{
var userTask = UserClass.GetUserInfo();
var user = await userTask;
if (user.ReadOnly)
{
// code to execute
}
return View();
}
In this example, GetUserInfo
returns a Task
, which is awaited to get the actual CurrentUserData
object. This allows you to access the ReadOnly
property of the CurrentUserData
object.
-
استخدام الرمز (_) في لامبدا C#13/03/2024
-
تحويل كود Java إلى C#: حل مشكلة CS100126/03/2024
Make sure your controller action is marked as async
to use await
, and you should be able to access the properties of the object returned by your async method.
المزيد من المعلومات
عند استخدام الدوال التي تعيد Task
، يتعين عليك استخدام الكلمة المفتاحية await
للانتظار حتى يتم اكتمال الدالة الخاصة بها. هذا يعني أن الدالة تعمل بشكل غير متزامن، ولا يتوفر النتيجة على الفور. فيما يلي كيفية تعديل كودك للعمل مع الدالة الجديدة التي تعيد Task
:
csharppublic async Task YourControllerAction()
{
var userTask = UserClass.GetUserInfo();
var user = await userTask;
if (user.ReadOnly)
{
// code to execute
}
return View();
}
في هذا المثال، تعيد GetUserInfo
نوع Task
، ويتم انتظارها باستخدام await
للحصول على الكائن CurrentUserData
الفعلي. هذا يتيح لك الوصول إلى خاصية ReadOnly
لكائن CurrentUserData
.
تأكد من تحديد إجراء تحكمك كـ async
لاستخدام await
، وبذلك يمكنك الوصول إلى خصائص الكائن الذي تعيده الدالة الغير متزامنة الخاصة بك.