ConcurrencyMode Перечисление

Определение

Указывает, поддерживает ли класс службы режимы операций с одним потоком или несколькими потоками.

public enum class ConcurrencyMode
public enum ConcurrencyMode
type ConcurrencyMode = 
Public Enum ConcurrencyMode
Наследование
ConcurrencyMode

Поля

Имя Значение Описание
Single 0

Экземпляр службы является однопоточным и не принимает повторные вызовы. InstanceContextMode Если свойство равноSingle, а во время вызова службы экземпляра поступают дополнительные сообщения, эти сообщения должны ждать, пока служба не будет доступна или пока не истекает время ожидания.

Reentrant 1

Экземпляр службы является однопоточным и принимает повторные вызовы. Повторная служба принимает вызовы при вызове другой службы; Поэтому необходимо оставить состояние объекта согласованным перед выносками и убедиться, что локальные данные операции действительны после выносок. Обратите внимание, что экземпляр службы разблокирован только путем вызова другой службы через канал WCF. В этом случае вызываемая служба может повторно войти в первую службу с помощью обратного вызова. Если первая служба не повторна, последовательность вызовов приводит к взаимоблокировке. Дополнительные сведения см. в ConcurrencyMode.

Multiple 2

Экземпляр службы состоит из нескольких потоков. Гарантии синхронизации не выполняются. Так как другие потоки могут изменять объект службы в любое время, необходимо всегда обрабатывать синхронизацию и согласованность состояния.

Примеры

В следующем примере кода показано, как использовать single, Reentrant и Multiple. Этот пример не компилируется без реальной реализации, но демонстрирует тип потоковых гарантий, что WCF делает и что означает для кода операции.

using System;
using System.ServiceModel;

[ServiceContract]
public interface IHttpFetcher
{
  [OperationContract]
  string GetWebPage(string address);
}

// These classes have the invariant that:
//     this.slow.GetWebPage(this.cachedAddress) == this.cachedWebPage.
// When you read cached values you can assume they are valid. When
// you write the cached values, you must guarantee that they are valid.
// With ConcurrencyMode.Single, WCF does not call again into the object
// so long as the method is running. After the operation returns the object
// can be called again, so you must make sure state is consistent before
// returning.
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single)]
class SingleCachingHttpFetcher : IHttpFetcher
{
    string cachedWebPage;
    string cachedAddress;
    readonly IHttpFetcher slow;

    public string GetWebPage(string address)
    {
        // <-- Can assume cache is valid.
        if (this.cachedAddress == address)
        {
            return this.cachedWebPage;
        }

        // <-- Cache is no longer valid because we are changing
        // one of the values.
        this.cachedAddress = address;
        string webPage = slow.GetWebPage(address);
        this.cachedWebPage = webPage;
        // <-- Cache is valid again here.

        return this.cachedWebPage;
        // <-- Must guarantee that the cache is valid because we are returning.
    }
}

// With ConcurrencyMode.Reentrant, WCF makes sure that only one
// thread runs in your code at a time. However, when you call out on a
// channel, the operation can get called again on another thread. Therefore
// you must confirm that state is consistent both before channel calls and
// before you return.
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Reentrant)]
class ReentrantCachingHttpFetcher : IHttpFetcher
{
  string cachedWebPage;
  string cachedAddress;
  readonly SlowHttpFetcher slow;

  public ReentrantCachingHttpFetcher()
  {
    this.slow = new SlowHttpFetcher();
  }

  public string GetWebPage(string address)
  {
    // <-- Can assume that cache is valid.
    if (this.cachedAddress == address)
    {
        return this.cachedWebPage;
    }

    // <-- Must guarantee that the cache is valid, because
    // the operation can be called again before we return.
    string webPage = slow.GetWebPage(address);
    // <-- Can assume cache is valid.

    // <-- Cache is no longer valid because we are changing
    // one of the values.
    this.cachedAddress = address;
    this.cachedWebPage = webPage;
    // <-- Cache is valid again here.

    return this.cachedWebPage;
    // <-- Must guarantee that cache is valid because we are returning.
  }
}

// With ConcurrencyMode.Multiple, threads can call an operation at any time.
// It is your responsibility to guard your state with locks. If
// you always guarantee you leave state consistent when you leave
// the lock, you can assume it is valid when you enter the lock.
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple)]
class MultipleCachingHttpFetcher : IHttpFetcher
{
  string cachedWebPage;
  string cachedAddress;
  readonly SlowHttpFetcher slow;
  readonly object ThisLock = new object();

  public MultipleCachingHttpFetcher()
  {
    this.slow = new SlowHttpFetcher();
  }

  public string GetWebPage(string address)
  {
    lock (this.ThisLock)
    {
      // <-- Can assume cache is valid.
      if (this.cachedAddress == address)
      {
          return this.cachedWebPage;
          // <-- Must guarantee that cache is valid because
          // the operation returns and releases the lock.
      }
      // <-- Must guarantee that cache is valid here because
      // the operation releases the lock.
    }

    string webPage = slow.GetWebPage(address);

    lock (this.ThisLock)
    {
      // <-- Can assume cache is valid.

      // <-- Cache is no longer valid because the operation
      // changes one of the values.
      this.cachedAddress = address;
      this.cachedWebPage = webPage;
      // <-- Cache is valid again here.

      // <-- Must guarantee that cache is valid because
      // the operation releases the lock.
    }

    return webPage;
  }
}

Комментарии

ConcurrencyMode используется вместе со свойством, ConcurrencyMode чтобы указать, поддерживает ли класс службы однопоточный или многопоточный режим операции. Однопоточная операция может быть повторной или повторной.

В следующей таблице показано, когда Windows Communication Foundation (WCF) разрешает вызывать операцию, пока выполняется другая, в зависимости от значения ConcurrencyMode.

Значение concurrencyMode Можно ли вызвать новую операцию?
Single "Никогда".
Повторная реентантная Только при вызове другой службы или обратного вызова.
Множественный Всегда.

Применяется к