2

さまざまなタスクを並行して実行するある種のスケジューラを書いています。IoC コンテナーとして MEF を使用します。ObjectContext の静的インスタンスを共有するのは得策ではないことがわかっているため、スレッドごとにインスタンスを作成することにしました。私は次のように実装しました:

[Export(typeof(IDatabaseFactory))]
[PartCreationPolicy(CreationPolicy.Shared)]
public class DatabaseFactory : IDatabaseFactory
{
    [Import]
    public IServiceResolver ServiceResolver { get; set; }

    [ThreadStatic]
    private static IEntityModel _dataContext;

    public IEntityModel Get()
    {
        if (_dataContext == null)
        {
            Debug.WriteLine("*************************");
            Debug.WriteLine(string.Format("Created Context Instance on Thread {0}", Thread.CurrentThread.ManagedThreadId));
            Debug.WriteLine("*************************");
        }

        return _dataContext ?? (_dataContext = ServiceResolver.GetService<IEntityModel>());
    }

    public void Dispose()
    {
        Debug.WriteLine("^^^^^^^^Disposing Context^^^^^^^^");

        if (_dataContext != null)
        {
            _dataContext.Dispose();
            _dataContext = null;
        }
    }
}

_dataContext フィールドの ThreadStatic 属性に注目してください。このコードは次の出力で失敗します。

*************************
Created Context Instance on Thread 9
*************************
-- Running Main Thread on thread 9
-- Scheduling servicetask of type ActiveDirectorySynchronisationServiceTask on thread 14
-- Scheduling servicetask of type LogCleanerServiceTask on thread 15
-- Scheduling servicetask of type TranscriptParseServiceTask on thread 17
-- Scheduling servicetask of type MailServiceTask on thread 16
*************************
*************************
Created Context Instance on Thread 15
*************************
Created Context Instance on Thread 17
*************************
Created Context Instance on Thread 16
*************************
*************************

次のエラーメッセージが表示されます:

{"The transaction operation cannot be performed because there are pending requests working on this transaction."}

実際のエラーは常に同じであるとは限らないことに注意してください (「基になるプロバイダーがオープンに失敗した」など)、これはマルチスレッドの問題であると確信しています。しかし、問題がわかりませんか?

接続は ObjectContext のインスタンス間で共有されますか? EF4.0、SQL Server Express 2008 を使用しています

4

2 に答える 2

0

私はこの問題の解決策を見つけました。[PartCreationPolicy(CreationPolicy.NonShared)]ObjectContextクラス定義にを追加しました。おそらく、この属性を明示的に定義しないことにより、共有参照が使用されました。

于 2012-12-08T10:31:36.117 に答える
0

MARS (複数のアクティブな結果セット)、 http: //msdn.microsoft.com/en-us/library/h32h3abf(v=vs.80).aspx が必要です

EF は、可能であれば SQL への接続を共有しようとします。これには、接続文字列レベルで上記の機能を有効にする必要があります。この問題が実際に発生するのは、同時に複数のアクティブなコンテキストがある場合 (マルチスレッド アプリケーションまたは適切に閉じられていないコンテキスト) のみです。

于 2012-12-06T14:02:50.813 に答える