且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在后台线程火灾事件

更新时间:2023-10-13 23:01:40

这是很简单的事:

public class Foo
{
    public event Action MyEvent;

    public void FireEvent()
    {
        Action myevent = MyEvent;
        if (myevent != null)
        {
            Task.Factory.StartNew(() => myevent())
                .ContinueWith(t =>
                {
                    //TODO code to run in UI thread after event runs goes here
                }, CancellationToken.None
                , TaskContinuationOptions.None
                , TaskScheduler.FromCurrentSynchronizationContext());
        }
    }
}

如果您正在使用C#5.0,您可以使用等待这简化了这个code:

If you're using C# 5.0 you can use await which simplifies this code:

public class Foo
{
    public event Action MyEvent;

    public async Task FireEvent()
    {
        Action myevent = MyEvent;
        if (MyEvent != null)
        {
            await Task.Run(() => myevent());
            //TODO code to run in UI thread after event runs goes here
        }
    }
}

如果您不需要code在UI线程中运行启动后,事件处理程序全部建成,它可以代替保持在同一时间在UI线程上走,还可以简化code到刚:

If you don't need the code running in the UI thread to start after the event handlers are all completed, and it can instead keep going on the UI thread at the same time, you can also simplify the code to just:

public class Foo
{
    public event Action MyEvent;

    public void FireEvent()
    {
        Action myevent = MyEvent;
        if (MyEvent != null)
        {
            Task.Factory.StartNew(() => myevent());

            //TODO code to run in UI thread while event handlers run goes here
        }
    }
}