سؤال

أنا أستهلك مورد طرف ثالث (A .dll) في خدمة ويب ، ومشكلتي هي أن استدعاء هذا المورد (استدعاء الطريقة) يتم تنفيذه غير متزامن - أحتاج إلى الاشتراك في حدث ما ، للحصول على الإجابة طلبي. كيف أفعل ذلك في خدمة الويب AC#؟

تحديث:

فيما يتعلق إجابة صني:

لا أريد أن أجعل خدمة الويب الخاصة بي غير متزامنة.

هل كانت مفيدة؟

المحلول

إذا كان مكون الطرف الثالث لا يدعم نموذج البرمجة غير المتزامن القياسي (أي أنه لا يستخدم IASyncresult) ، فلا يزال بإمكانك تحقيق التزامن باستخدام Autoresetevent أو ManualResetEvent. للقيام بذلك ، أعلن عن حقل من النوع Autoresetevent في فئة خدمة الويب الخاصة بك:

AutoResetEvent processingCompleteEvent = new AutoResetEvent();

ثم انتظر الإشارة إلى الحدث بعد الاتصال بمكون الطرف الثالث

// call 3rd party component
processingCompleteEvent.WaitOne()

وفي معالج أحداث رد الاتصال ، أشار إلى الحدث للسماح لخيط الانتظار باستمرار التنفيذ:

 processingCompleteEvent.Set()

نصائح أخرى

على افتراض أن مكونك الثالث من الطرف هو استخدام نمط نموذج البرمجة غير المتزامن المستخدم في إطار .NET ، يمكنك القيام بشيء من هذا القبيل

    HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://www.stackoverflow.com");
    IAsyncResult asyncResult = httpWebRequest.BeginGetResponse(null, null);

    asyncResult.AsyncWaitHandle.WaitOne();

    using (HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.EndGetResponse(asyncResult))
    using (StreamReader responseStreamReader = new StreamReader(httpWebResponse.GetResponseStream()))
    {
        string responseText = responseStreamReader.ReadToEnd();
    }

نظرًا لأنك بحاجة إلى عملية خدمة الويب الخاصة بك لمنعك ، يجب عليك استخدام iASyncresult.Asyncwaithandle بدلاً من رد الاتصال حتى تكتمل العملية.

من مستندات MSDN:

using System;
using System.Web.Services;

[WebService(Namespace="http://www.contoso.com/")]
public class MyService : WebService {
  public RemoteService remoteService;
  public MyService() {
     // Create a new instance of proxy class for 
     // the XML Web service to be called.
     remoteService = new RemoteService();
  }
  // Define the Begin method.
  [WebMethod]
  public IAsyncResult BeginGetAuthorRoyalties(String Author,
                  AsyncCallback callback, object asyncState) {
     // Begin asynchronous communictation with a different XML Web
     // service.
     return remoteService.BeginReturnedStronglyTypedDS(Author,
                         callback,asyncState);
  }
  // Define the End method.
  [WebMethod]
  public AuthorRoyalties EndGetAuthorRoyalties(IAsyncResult
                                   asyncResult) {
   // Return the asynchronous result from the other XML Web service.
   return remoteService.EndReturnedStronglyTypedDS(asyncResult);
  }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top