模仿MessageBox-等待用户选择 [英] Imitate MessageBox - waiting for user's choice

查看:87
本文介绍了模仿MessageBox-等待用户选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我主要使用Windows Phone,并且尝试创建类似于MessageBox的东西-识别并等待用户选择的小窗口(调用窗口的线程等待).我发现了三种实现目标的方法:

第一-TaskCompletionSource
在这种情况下,我的任务如下所示:

I'm working mostly with Windows Phone and I'm trying to create something similar to MessageBox - small window that apperas and waits for user's choice (the Thread that invoked window waits). I found three ways how I can achive this goal:

FIRST - TaskCompletionSource
In this case my Task looks like this:

TaskCompletionSource<bool> taskComplete = new TaskCompletionSource<bool>();
private async Task myTask1()
{
   window.Show(); // Show window
   await taskComplete.Task;
   //some job run after User's choice
   MessageBox.Show("Job finished");
}

我的窗口的关闭事件:

private void WindowClosedEvent1(object sender, EventArgs e)
{
   taskComplete.SetResult(true);
}

第二-SemaphoreSlim
我的任务和事件:

SECOND - SemaphoreSlim
My Task and event:

private SemaphoreSlim mySemaphore = new SemaphoreSlim(0, 1);
private async Task myTask2()
{
    window.Show(); // Show window
    await mySemaphore.WaitAsync();
    //some job run after User's choice
    MessageBox.Show("Job finished");
}

private void WindowClosedEvent2(object sender, EventArgs e)
{
    mySemaphore.Release();
}

第三方-EventWaitHandle:
我的任务和事件:

THIRD - EventWaitHandle:
My Task and Event:

EventWaitHandle waitForUser = new EventWaitHandle(false, EventResetMode.AutoReset, "myEventName");
private async Task myTask3()
{
    window.Show(); // Show window
    await Task.Run(() => waitForUser.WaitOne());
    //some job run after User's choice
    MessageBox.Show("Job finished");
}

private void WindowClosedEvent3(object sender, EventArgs e)
{
    waitForUser.Set();
}

所有这三种方法均有效,但我无法决定使用哪种方法.我主要认为1)或2)将是最佳选择.在某些情况下,这三种方法中的任何一种都会引起麻烦吗?有人尝试过这样的事情吗?

All three methods work, but I cannot decide which to use. I'm mostly thinking that 1) or 2) will be the best choice. Can any of those three methods cause troubles in some circumstances? Has anybody tried something like this?

推荐答案

带有TaskCompletionSource的变体#1足以满足要求,这就是TaskCompletionSource的用途. #2和#3不必要复杂,尤其是Task.Run(..)的#3,它浪费了池线程来进行阻塞等待.

The variant #1 with TaskCompletionSource is enough for this, that's what TaskCompletionSource is for. #2 and #3 are unnecessary complex, especially #3 with Task.Run(..), which is wasting a pool thread for a blocking wait.

由于WP中的Popup没有模态,所有这三种方法都可能存在一个主要问题:重新进入.例如,如果在单击按钮时调用myTask2(),则不会阻止用户再次单击该按钮,这将启动另一个myTask2().您的应用的UI工作流程应解决此问题.

Because there is no modality for Popup in WP, all three approaches potentially have one major issue: re-entrancy. E.g., if myTask2() is called upon a button click, nothing prevents user from clicking that button again, which would start another myTask2(). The UI workflow of your app should account for this. This is discussed here.

这篇关于模仿MessageBox-等待用户选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆