开发者

BackgroundWorkerCompleted doesnt seem to run in main thread?

I'm writing a addin for outlook which has some network code for API calls, which is why I have several classes extending the BackgroundWorker class, each encapsulating a API call. The code looks like this for a Api Call:

public class ApiLogin : BackgroundWorker
{
    private void ThisAddInStartup(object sender, EventArgs e)
    {
        this.DoWork += BgWorkerDoWork;
        this.RunWorkerCompleted += BgWorkerCompleted;
    }

    private void BgWorkerDoWork(object sender, DoWorkEventArgs e)
    {
        //Perform network call on the background thread
        var logged_in = ApiRequests.login();
        e.Result = logged_in;
    }

    //This should run in the main thread, no?
    private void BgWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        var logged_in = (bool)e.Result;

        //Do stuff in main thread, hopefully..

        //Investigate开发者_StackOverflow社区 if this runs in the main thread since it should block Outlook, no?
        Thread.Sleep(50000);
    }
}

And the code looks like this for my Outlook Addin:

public class ThisAddin
{

    private ApiLogin _loginWorker;

    private void ThisAddInStartup(object sender, EventArgs e)
    {
       _loginWorker = new ApiLogin();
       _loginWorker.RunWorkerAsync();
    }
}

When I run my addin I expect outlook to block for 50 seconds since I have a Thread.Sleep(50000) in the background workers Completed-event handler, but this does not happen. This implies to me that this code does not run in the main thread? I have searched for a solution in vain and now I would like to know if anyone here knows what might be the problem?


BackgroundWorker requires a synchronization provider to determine on which thread the RunWorkerCompleted event runs. It uses SynchronizationContext.Current. Odds are very high that this property is null when your plugin starts. So nothing is getting synchronized and the event runs on a threadpool thread.

There are two synchronization providers in the .NET framework, respectively the one for Winforms and the one for WPF. They need their respective message loop to do the thread marshaling, they assign SynchronizationContext.Current in their Application.Run() method. You have neither. The simplest solution is to create a Winforms Form and call its ShowDialog() method. That in itself already blocks the Outlook user interface. Also good to provide some feedback to the user so she doesn't have to guess why Outlook stopped responding.


I would certainly expect it to run on the same thread as the ThisAddinStartup method: you can verify this by tracing the thread id in both places.

As for Outlook, maybe it's running your add-in on a separate UI thread.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜