7

我正在使用 Web 服务,因此我有必要延长会话长度/重新连接并获取大型数据集等。有时这可能很长,所以我希望它在一个单独的线程中异步更新 UI。

我似乎无法使用同步上下文来调用我的 UI 线程上的方法。我有它,我已经将我的 UIThread 上下文传递给我的线程,现在我想更新 UI 线程上的一些标签等。我已经阅读了大量的帖子,但似乎没有人解释如何简单地将一些参数传递回方法,或者他们可能这样做了,但我太累/太愚蠢了,看不到它。

//在主UI线程上

public void updateConnStatus(string conn_name, bool connected)
{
        switch (conn_name)
        {
            case "Conn" : if (connected == true){ //do something} break;

//在单独的线程上

uiContext.Post( //something to do with delegates in here that eludes me );

如果有人可以简单地解释我如何将 sendOrPostCallBack 链接到原始方法,我将不胜感激。

谢谢

编辑:

我设法让代码运行并尝试触发事件,它填充了我的自定义 eventArgs 好,但要么它说 updateUIConnStatus 尚未实例化,需要更多调查:o

public void updateUIThread(string conn, bool connected)
    {
       uiContext.Post(new SendOrPostCallback((o) => { updateConnStatus(this, new MyEventArgs<String, Boolean>(conn, connected)); }), null);
    }

public class MyEventArgs<T, U> : EventArgs
    {
        private T _val1; private U _val2;
        public  MyEventArgs(T value1, U value2) { _val1 = value1; _val2 = value2; }
        public T val1 { get { return _val1;} }
        public U val2 { get {return _val2;} }
    }

public event EventHandler<MyEventArgs<String, Boolean>> updateConnStatus = Delegate {};

//现在在 UI 线程上

 public void updateConnStatus(object sender, MyEventArgs<String,Boolean> e)
    {
        switch (e.val1)
        {
            case "Conn1" :
                if (e.val2 == true)
                {
4

2 回答 2

19

您需要一个 SendOrPostCallback 类型的委托。这很尴尬,它只需要一个object类型的参数。您绝对应该查看 .NET 4 中提供的 Task<> 类,以使其更容易。或者使用 lambda,如下所示:

        string conn_name = "foo";
        uiContext.Post(new SendOrPostCallback((o) => {
            updateConnStatus(conn_name, true);
        }), null);

{ 大括号 } 之间的代码在 UI 线程上执行。

于 2012-08-19T18:47:29.387 回答
7

通常,您在 UI 线程上创建类型的实例(例如 ViewModels),因此您可以将 SynchronizationContext 或 TaskScheduler(最好是恕我直言)保存到私有字段,然后在需要时进行比较...

private readonly SynchronizationContext _syncContext = SynchronizationContext.Current;
private readonly TaskScheduler _scheduler = TaskScheduler.Current;

void OnSomeEvent(object sender, EventArgs e)
{
    if (_syncContext != SynchronizationContext.Current)
    {
        // Use Send if you need to get something done as soon as possible.
        // We'll be polite by using Post to wait our turn in the queue.
        _syncContext.Post(o => DoSomething(), null);
        return;
    }
    // Call directly if we are already on the UI thread
    DoSomething();
}

void OnSomeOtherEvent(object sender, MyEventArgs e)
{
    var arg1 = e.Arg1; // "Hello "
    var arg2 = e.Arg2; // {"World", "!"};

    // Process args in the background, and then show the result to the user...
    // NOTE: We don't even need to check the context because we are passing
    // the appropriate scheduler to the continuation that shows a MessageBox.

    Task<string>.Factory.StartNew(() => ReturnSomething(arg1, arg2))
        .ContinueWith(t => MessageBox.Show(t.Result), _scheduler);
}

void DoSomething() { MessageBox.Show("Hello World!"); }

string ReturnSomething(string s, IEnumerable<string> list)
{
    return s + list.Aggregate((c, n) => c + n);
}
于 2013-09-23T17:50:54.260 回答