gpt4 book ai didi

c# - 在单独的线程中调用方法

转载 作者:太空狗 更新时间:2023-10-30 00:05:41 24 4
gpt4 key购买 nike

我需要在单独的线程中调用类方法。该方法有一个参数和一个返回值。

详情

我有一个带有两个文本框的表单。用户将值放入第一个 TextBox 并在第二个 TextBox 中获取结果:

 private void tbWord_TextChanged(object sender, TextChangedEventArgs e)
{
tbResponce.Text = Wiki.DoWork(tbWord.Text);
}

Wiki 类必须使用 Wikipedia API:

public class Wiki
{
private class State
{
public EventWaitHandle eventWaitHandle = new ManualResetEvent(false);
public String result;
public String word;
}

private static void PerformUserWorkItem( Object stateObject )
{
State state = stateObject as State;

if(state != null)
{
Uri address = new Uri("http://en.wikipedia.org/w/api.php?action=opensearch&search=" + state.word);
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
HttpWebResponse responce = (HttpWebResponse)request.GetResponse();

StreamReader myStreamReader = new StreamReader(responce.GetResponseStream(), Encoding.GetEncoding(1251));
state.result = myStreamReader.ReadToEnd();

state.eventWaitHandle.Set();
}
}

public static String DoWork(String _word)
{
State state = new State();
state.word = _word;

ThreadPool.QueueUserWorkItem(PerformUserWorkItem, state);
state.eventWaitHandle.WaitOne();
return state.result;
}
}

问题

当用户按下 tbWord 中的键时,主窗体会卡住并等待 Wiki 类完成所有工作。

如何异步运行 DoWork?

最佳答案

或者像这样使用 TPL:

private void tbWord_TextChanged(object sender, TextChangedEventArgs e) 
{
Task.Factory.StartNew(() =>
{
return Wiki.DoWrok(tbWord.Text);
}).ContinueWith(taskState =>
{
tbResponce.Text = taskState.Result;
}, TaskScheduler.FromCurrentSynchronizationContext());
}

参见:http://msdn.microsoft.com/en-us/library/dd997394.aspx

关于c# - 在单独的线程中调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9359216/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com