البرمجة

استخدام الدوال مع إرجاع Task في C#

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:

csharp
public 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.

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:

csharp
public 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، وبذلك يمكنك الوصول إلى خصائص الكائن الذي تعيده الدالة الغير متزامنة الخاصة بك.

مقالات ذات صلة

زر الذهاب إلى الأعلى
إغلاق

أنت تستخدم إضافة Adblock

يرجى تعطيل مانع الإعلانات حيث أن موقعنا غير مزعج ولا بأس من عرض الأعلانات لك فهي تعتبر كمصدر دخل لنا و دعم مقدم منك لنا لنستمر في تقديم المحتوى المناسب و المفيد لك فلا تبخل بدعمنا عزيزي الزائر